keys_seen = []
for D in L: #loop through the list
for key in D.keys(): #loop through each dictionary's keys
if key not in keys_seen: #if we haven't seen this key before, then...
keys_seen.append(key) #add it to the list of keys seen
for D1 in L: #loop through the list again
for key in keys_seen: #loop through the list of keys that we've seen
if key not in D1: #if the dictionary is missing that key, then...
D1[key] = 0 #add it and set it to 0
您将需要进行两次传递:1次以获取所有键的并集,另一次用于添加缺少的键:
它使用一个“空”字典作为基础来快速生成所有键;这个字典的新副本加上一个原始字典将生成您想要的输出。在
请注意,这假设您的键始终是顺序的。如果不是,则可以生成所有现有键的并集:
^{pr2}$演示:
或设定方法:
上面使用
dict(d1, **d2)
将两个字典合并为一个新字典的方法在Python2中始终有效。在Python中,对可以使用这种技巧的键类型设置了3个附加约束;第二个字典只允许使用字符串键。对于本例,如果有数字键,则可以使用它们的字典视图的并集来代替:小心一点:改变L
这只是一个解决方案,但我认为它简单明了。请注意,它会对字典进行适当的修改,因此,如果您希望将它们复制到中,请告诉我,我会相应地进行修改。在
相关问题 更多 >
编程相关推荐