4

我有一本形式的字典:

d = {123:{2:1,3:1}, 124:{3:1}, 125:{2:1},126:{1:1}}

所以,让我们看看 2nd degree key..

123--> 2,3
124--> 3
125--> 2
126--> 1

所以唯一的二阶键的总数是:

1,2,3

现在,我想将此字典修改为

 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 字典中不存在所有 2 阶键。添加值为 0 的键。

这样做的pythonic方法是什么?谢谢

4

4 回答 4

9
keyset = set()
for k in d:
    keyset.update(d[k])

for k in d:
    for kk in keyset:
        d[k].setdefault(kk, 0)
于 2012-10-18T17:12:21.880 回答
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}}

这里使用设置差异来获取丢失的键,然后update()是字典:

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])
于 2012-10-18T17:16:28.277 回答
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)
于 2012-10-18T17:38:53.507 回答
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)
于 2012-10-18T17:14:24.653 回答