在Python中的字典中添加缺失的键 [英] Adding missing keys in dictionary in Python

查看:305
本文介绍了在Python中的字典中添加缺失的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表:

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

如您所见,字典的长度不同。我需要的是添加缺失的键:每个字典的值,使它们具有相同的长度:

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

意味着为缺失的值添加零。最大长度不是提前给出的,所以只能通过列表来迭代。



我试图用默认值来做某事,如 L1 = defaultdict(L)但似乎我不明白它是如何工作的。

解决方案

有点谨慎:更改L

 >>> allkeys = frozenset()。union(* L)
>>>对于我在L中:
...在所有键中的j:
...如果j不在我:
...我[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}]


I have a list of dictionaries:

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

As you can see, the dictionaries have different length. What I need is to add missing keys:values to every dictionary to make them being with the same length:

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

Means to add zeros for missing values. The maximum length isn't given in advance, so one may get it only iterating through the list.

I tried to make something with defaultdicts, like L1 = defaultdict(L) but it seems I don't understand properly how does it work.

解决方案

a bit of caution: changes 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}]

这篇关于在Python中的字典中添加缺失的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆