0

我有以下字典列表:

list1 = [
            { 'n1': ('e1','e2','e3') },
            { 'n2': ('e1','e2') },
            { 'n3': ('e2','e3','e4') }
        ]

我需要将其转换为:

list2 = [
            { 'e1': ('n1','n2') },
            { 'e2': ('n1','n2','n3') },
            { 'e3': ('n3',) },
            { 'e4': ('n3',) }
         ]

有什么简短而聪明的方法可以做到这一点吗?

4

2 回答 2

0

I think setdefault can be useful for You in this task. If You need dict as result. You can use something like this.

res = {}
for d in list1: 
    for k, v in d.iteritems():
        for i in v:
            res.setdefault(i, []).append(k)

If You need list of dictionaries you can use list comprehension after this

res = [{k:v} for k, v in res.iteritems()]

If You insist on list as values cast lists to tuples in last list comrehensions

res = [{k: tuple(v)} for k, v in res.iteritems()]
于 2013-06-21T19:16:00.533 回答
0

像这样的东西:

>>> from itertools import chain
>>> from collections import defaultdict
>>> vals = set(chain.from_iterable(y for x in list1 for y in x.values()))
>>> dic = defaultdict(list)
>>> for x in vals:
...     for y in list1:
...         for k,v in y.items():
...             if x in v:
...                 dic[x].append(k)
...                 
>>> dic
defaultdict(<type 'list'>,
{'e4': ['n3'],
 'e1': ['n1', 'n2'],
 'e3': ['n1', 'n3'],
 'e2': ['n1', 'n2', 'n3']})
于 2013-06-21T18:57:23.563 回答