0

我正在尝试编写字典理解。

我有一本这样的字典:

main_dict = {
    'A' : {'key1' : 'valueA1', 'key2' : 'valueA2'},
    'B' : {'key2' : 'valueB2', 'key3' : 'valueB3'},
    'C' : {'key3' : 'valueC3', 'key1' : 'valueC1'}}

我想执行以下逻辑:

d = {}
for k_outer, v_outer in main_dict.items():
    for k_inner, v_inner in v_outer.items():
        if k_inner in d.keys():
            d[k_inner].append([k_outer, v_inner])
        else:
            d[k_inner] = [[k_outer, v_inner]]

这会产生以下结果:

{'key3': [['C', 'valueC3'], ['B', 'valueB3']], 
 'key2': [['A', 'valueA2'], ['B', 'valueB2']], 
 'key1': [['A', 'valueA1'], ['C', 'valueC1']]}

(我知道我可以使用defaultdict(list),但这只是一个例子)

我想使用 dict-comprehension 执行逻辑,到目前为止,我有以下内容:

d = {k : [m, v] for m, x in main_dict.items() for k, v in x.items()}

这不起作用,它只给我以下输出:

{'key3' : ['B', 'valueB3'],
'key2' : ['B', 'valueB2'],
'key1' : ['C', 'valueC1']}

这是为每个 inner_key 找到的最后一个实例...

我不知道如何正确执行此嵌套列表理解。我尝试了多种变体,都比上一个更糟。

4

4 回答 4

2

你可以尝试这样的事情:

In [61]: main_dict
Out[61]: 
{'A': {'key1': 'valueA1', 'key2': 'valueA2'},
 'B': {'key2': 'valueB2', 'key3': 'valueB3'},
 'C': {'key1': 'valueC1', 'key3': 'valueC3'}}

In [62]: keys=set(chain(*[x for x in main_dict.values()]))

In [64]: keys
Out[64]: set(['key3', 'key2', 'key1'])

In [63]: {x:[[y,main_dict[y][x]] for y in main_dict if x in main_dict[y]] for x in keys}
Out[63]: 
{'key1': [['A', 'valueA1'], ['C', 'valueC1']],
 'key2': [['A', 'valueA2'], ['B', 'valueB2']],
 'key3': [['C', 'valueC3'], ['B', 'valueB3']]}

使用更具可读性的解决方案dict.setdefault

In [81]: d={}

In [82]: for x in keys:
    for y in main_dict:
       if x in main_dict[y]:
           d.setdefault(x,[]).append([y,main_dict[y][x]])
   ....:            

In [83]: d
Out[83]: 
{'key1': [['A', 'valueA1'], ['C', 'valueC1']],
 'key2': [['A', 'valueA2'], ['B', 'valueB2']],
 'key3': [['C', 'valueC3'], ['B', 'valueB3']]}
于 2013-01-06T11:43:38.097 回答
1

使用三个字典理解来完成这样的任务,第三个字典理解是结合前两个字典:

e = {k : [m, v] for m, x in main_dict.items() for k, v in x.items()}
f = {k : [m, v] for m, x in main_dict.items() for k, v in x.items() if [m,v] not in e.values()}
g = {k1 : [m, v] for k1,m in e.items() for k2,v in f.items() if k1==k2}
于 2013-01-06T12:08:44.847 回答
0

一种选择是使用itertools.groupby

from itertools import groupby
from operator import itemgetter

main_dict = {
    'A' : {'key1' : 'valueA1', 'key2' : 'valueA2'},
    'B' : {'key2' : 'valueB2', 'key3' : 'valueB3'},
    'C' : {'key3' : 'valueC3', 'key1' : 'valueC1'}}

## Pull inner key, outer key and value and sort by key (prior to grouping)
x = sorted([(k2, [k1, v2]) for k1, v1 in main_dict.items() for k2, v2, in v1.items()])

## Group by key. This creates an itertools.groupby object that can be iterated
## to get key and value iterables
xx = groupby(x, key=itemgetter(0))

for k, g in xx:
    print('{0} : {1}'.format(k, [r[1] for r in list(g)]))

根据您的数据和性能要求,排序可能并不理想,因此值得进行分析。

此外,它不会产生指定的 dict,而是 groupby 对象。这可能足以满足您的需求;迭代它会产生 key 和 iterables。

于 2013-01-06T13:35:36.337 回答
0

最后,这就是我使用的:

from collections import defaultdict

d = defaultdict(list)
for m, x in main_dict.items():
    for k, v in x.items():
        d[k].append((m, v))
于 2013-01-10T09:27:39.903 回答