【发布时间】:2019-03-12 16:15:57
【问题描述】:
这是一个简单的问题,但我对collections.defaultdict 的行为感到困惑。这是为了帮助我了解它是如何工作的。
这个问题是从这个有用的问题中推断出来的: How to merge a list of multiple dictionaries into a dictionary of lists?
现在假设我有一个字典列表。我想合并上述问题中详述的字典:
list_of_dictionaries2 = [[{0:3523, 1:3524, 2:3540, 4:3541, 5:3542},
{0:7245, 1:7246, 2:7247, 3:7248, 5:7249, 6:7250},
{1:20898, 2:20899, 3:20900, 4:20901, 5:20902}], [{0:3, 1:4, 2:5, 3:6}]]
预期的答案是这样的:
correct2 = [[{0:[3523, 7245], 1:[3524, 7246, 20898], 2:[3540, 7247, 20899],
3:[7248, 20900], 4:[3541, 20901], 5:[3542, 7249, 20902], 6:[7250]}],
[{0:3, 1:4, 2:5, 3:6}]]
以前,对于单个字典列表,我们通过创建一个带有默认值作为列表的空字典来解决这个问题,即我们使用collections.defaultdict(list)。
鉴于这种情况是一个列表列表,我认为另一个 for 循环将是解决方案,将字典附加到一个空列表中:
from collections import defaultdict
correct2 = defaultdict(list)
empty = []
for smaller_list in list_of_dictionaries2:
for d in smaller_list:
for k,v in d.items():
correct2[k].append(v)
empty.append(correct2)
这是非常错误的。
>>> print(empty)
[defaultdict(<class 'list'>, {0: [3523, 7245, 3], 1: [3524, 7246, 20898, 4],
2: [3540, 7247, 20899, 5], 4: [3541, 20901], 5: [3542, 7249, 20902],
3: [7248, 20900, 6], 6: [7250]}), defaultdict(<class 'list'>,
{0: [3523, 7245, 3], 1: [3524, 7246, 20898, 4], 2: [3540, 7247, 20899, 5],
4: [3541, 20901], 5: [3542, 7249, 20902], 3: [7248, 20900, 6], 6: [7250]})]
看起来所有字典都合并了。并且有两个副本。这不是我想要的。
如何为每个单独的列表执行此操作,如上所示?我在哪里理解有误?
【问题讨论】:
标签: python python-3.x dictionary defaultdict dictionary-comprehension