我有一个表格字典:
d = {123:{2:1,3:1}, 124:{3:1}, 125:{2:1},126:{1:1}}
所以,让我们看看二度键..
123--> 2,3
124--> 3
125--> 2
126--> 1
所以唯一的二阶键的总数是:
1,2,3
现在,我想将此dict修改为
d = {123:{1:0,2:1,3:1}, 124:{1:0,2:0,3:1}, 125:{1:0,2:1,3:0},126:{1:1,2:0,3:0}}
所以基本上所有的二阶键都没有出现在特定的2d dict中..添加值为0的键。
这样做的pythonic方法是什么? 感谢
答案 0 :(得分:9)
keyset = set()
for k in d:
keyset.update(d[k])
for k in d:
for kk in keyset:
d[k].setdefault(kk, 0)
答案 1 :(得分:3)
In [25]: d = {123:{2:1,3:1}, 124:{3:1}, 125:{2:1},126:{1:1}}
In [26]: se=set(y for x in d for y in d[x])
In [27]: for x in d:
foo=se.difference(d[x])
d[x].update(dict(zip(foo,[0]*len(foo))))
....:
....:
In [30]: d
Out[30]:
{123: {1: 0, 2: 1, 3: 1},
124: {1: 0, 2: 0, 3: 1},
125: {1: 0, 2: 1, 3: 0},
126: {1: 1, 2: 0, 3: 0}}
这里使用set difference来获取缺失的密钥,然后使用update()
dict:
In [39]: for x in d:
foo=se.difference(d[x])
print foo # missing keys per dict
set([1])
set([1, 2])
set([1, 3])
set([2, 3])
答案 2 :(得分:2)
我喜欢Ashwini Chaudhary的解决方案。
我对其进行了编辑,将评论中的所有建议与其他细微更改结合起来,以便了解我的偏好:
已编辑(将Steven Rumbalski的建议纳入此答案)。
all_second_keys = set(key for value in d.itervalues() for key in value)
for value in d.itervalues():
value.update((key,0) for key in all_second_keys if key not in value)
答案 3 :(得分:1)
import operator
second_order_keys = reduce(operator.__or__,
(set(v.iterkeys()) for v in d.itervalues()))
for v in d.itervalues():
for k in second_order_keys:
v.setdefault(k, 0)
或者,在Python 3中:
from functools import reduce
import operator
second_order_keys = reduce(operator.__or__,
(v.keys() for v in d.values()))
for v in d.values():
for k in second_order_keys:
v.setdefault(k, 0)