在Python中添加字典中的缺失键

2024-04-25 12:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单:

L = [{0:1,1:7,2:3,4:8},{0:3,2:6},{1:2,4:6}....{0:2,3:2}]. 

正如你所看到的,字典的长度不同。我需要的是加上失踪关键点:值到每一本字典的长度都是一样的:

^{pr2}$

表示为缺少的值加零。最大长度不是预先给定的,因此只能通过遍历列表获得它。在

我试着用defaultdicts做一些东西,比如L1 = defaultdict(L),但似乎我不明白它是如何工作的。在


Tags: l1列表字典关键点defaultdictpr2defaultdicts
3条回答

您将需要进行两次传递:1次以获取所有键的并集,另一次用于添加缺少的键:

max_key = max(max(d) for d in L)
empty = dict.fromkeys(range(max_key + 1), 0)
L1 = [dict(empty, **d) for d in L]

它使用一个“空”字典作为基础来快速生成所有键;这个字典的新副本加上一个原始字典将生成您想要的输出。在

请注意,这假设您的键始终是顺序的。如果不是,则可以生成所有现有键的并集:

^{pr2}$

演示:

>>> L = [{0: 1, 1: 7, 2: 3, 4: 8}, {0: 3, 2: 6}, {1: 2, 4: 6}, {0: 2, 3: 2}]
>>> max_key = max(max(d) for d in L)
>>> empty = dict.fromkeys(range(max_key + 1), 0)
>>> [dict(empty, **d) for d in L]
[{0: 1, 1: 7, 2: 3, 3: 0, 4: 8}, {0: 3, 1: 0, 2: 6, 3: 0, 4: 0}, {0: 0, 1: 2, 2: 0, 3: 0, 4: 6}, {0: 2, 1: 0, 2: 0, 3: 2, 4: 0}]

或设定方法:

>>> empty = dict.fromkeys(set().union(*L), 0)
>>> [dict(empty, **d) for d in L]
[{0: 1, 1: 7, 2: 3, 3: 0, 4: 8}, {0: 3, 1: 0, 2: 6, 3: 0, 4: 0}, {0: 0, 1: 2, 2: 0, 3: 0, 4: 6}, {0: 2, 1: 0, 2: 0, 3: 2, 4: 0}]

上面使用dict(d1, **d2)将两个字典合并为一个新字典的方法在Python2中始终有效。在Python中,对可以使用这种技巧的键类型设置了3个附加约束;第二个字典只允许使用字符串键。对于本例,如果有数字键,则可以使用它们的字典视图的并集来代替:

dict(d.items() | empty.items())  # Python 3 dictionary merge

小心一点:改变L

>>> allkeys = frozenset().union(*L)
>>> for i in L:
...    for j in allkeys:
...        if j not in i:
...            i[j]=0

>>> L
[{0: 1, 1: 7, 2: 3, 3: 0, 4: 8}, {0: 3, 1: 0, 2: 6, 3: 0, 4: 0}, {0: 0, 1: 2, 2:
 0, 3: 0, 4: 6}, {0: 2, 1: 0, 2: 0, 3: 2, 4: 0}]

这只是一个解决方案,但我认为它简单明了。请注意,它会对字典进行适当的修改,因此,如果您希望将它们复制到中,请告诉我,我会相应地进行修改。在

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

相关问题 更多 >