Python创建列表字典

标签 python dictionary

我想创建一个字典,其值是列表。例如:

{
  1: ['1'],
  2: ['1','2'],
  3: ['2']
}

如果我这样做:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d[j].append(i)

我得到一个 KeyError,因为 d[...] 不是一个列表。在这种情况下,我可以在分配 a 之后添加以下代码来初始化字典。

for x in range(1, 4):
    d[x] = list()

有没有更好的方法来做到这一点?假设我在进入第二个 for 循环之前不知道我需要的 key 。例如:

class relation:
    scope_list = list()
...
d = dict()
for relation in relation_list:
    for scope_item in relation.scope_list:
        d[scope_item].append(relation)

另一种选择是替换

d[scope_item].append(relation)

if d.has_key(scope_item):
    d[scope_item].append(relation)
else:
    d[scope_item] = [relation,]

处理此问题的最佳方法是什么?理想情况下,追加将“正常工作”。有没有什么方法可以表达我想要一个空列表的字典,即使我在第一次创建列表时不知道每个键?

最佳答案

您可以使用 defaultdict :

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
...   for j in range(int(i), int(i) + 2):
...     d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]

关于Python创建列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/960733/

相关文章:

java - 当设备中安装了 .apk 时,谷歌地图无法工作

python - 检查集合中是否有任何成员以 Python 中给定的前缀字符串开头

python - 使用 selenium 通过部分链接文本单击元素时遇到问题

python - 类型错误 : unhashable type: 'dict' Django

python - 如何使用 3 个列表在 Python 中创建嵌套字典

c++ - 将复杂值插入 C++ 中的映射

Python - 提高我的算法速度

python - Airflow/Composer - 在 zip 打包的 DAG 中找不到模板

python - 命令行 tar 和 Shutil.make_archive 之间的区别?

python - 如果查询不在 mySQL 数据库中,则显示错误消息