如何在Python中创建一个以列表为键的字典?

时间:2017-05-25 13:20:25

标签: python list dictionary vector range

我想在Python中创建一个字典,其中键是列表。

我想要面对的问题是我有一个包含多个整数值的列表(从1到300),并且根据不同的值范围,我想将它们转换为字符。例如:

  • 从1到100的值到字符' A'。
  • 从101到200的值到字符' B'。
  • 从201到300的值到字符' C'。

我试过这种方式,但它没有工作:

dictionary = {[1, 100]:'A', [101, 200]:'B', [201, 300]:'C'}

但我收到错误:

TypeError: unhashable type: 'list'

我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

将列表转换为元组。元组是可以清洗的。列表不是。

dictionary = {(1, 100):'A', (101, 200):'B', (201, 300):'C'}

答案 1 :(得分:0)

您可以使用列表,列表的JSON表示或列表的repr

>>> d1={repr([1, 100]):'A', repr([101, 200]):'B', repr([201, 300]):'C'}
>>> import json
>>> d2={json.dumps([1, 100]):'A', json.dumps([101, 200]):'B', json.dumps([201, 300]):'C'}
>>> d2
{'[101, 200]': 'B', '[1, 100]': 'A', '[201, 300]': 'C'}
>>> d1
{'[101, 200]': 'B', '[1, 100]': 'A', '[201, 300]': 'C'}

答案 2 :(得分:0)

我不知道我是否理解正确但您尝试将范围[1,300]中的整数列表转换为字符A,B,C的字符列表。取决于整数值。我不明白为什么你需要一个带有列表键的字典......

您可以使用简单的for循环和一些if语句来完成。

Outside loop = {{ element['#object'].get('field_section_theme').value }}

返回

import random

ints = [random.randint(1,300) for i in xrange(10)]

chars = []

for el in ints:
    if el > 0 and el <= 300:
        if el <= 100:
            chars.append("A")
        elif el <= 200:
            chars.append("B")
        else:
            chars.append("C")
    else:
        raise RuntimeError("element {} not in valid range.".format(el))

print(ints)
print(chars)