元组列表,第一个元组作为键,按键分组到字典中

时间:2012-10-22 16:13:46

标签: python list dictionary tuples grouping

我有一个元组列表。第一部分是可以重复或不重复的标识符。我想将这个列表处理成一个字典,用标识符键入。问题是,我一直无法考虑用密钥覆盖:

def response_items(self):
        ri = self.response_items_listing#(gets the list)          
        response_items = {}
        for k, g in groupby(ri, itemgetter(0)):
            x = list(g)
            l = [(xx[1],xx[2]) for xx in x]
            response_items[k] = l
        return response_items

e.g。列表如:

[('123', 'abc', 'def'),('123', 'efg', 'hij'),('456', 'klm','nop')]

将以

回来

{123:('efg', 'hij'), 456:('klm', 'nop')}

但我需要:

{123:[('abc', 'def'),('efg', 'hij')], 456:('klm', 'nop')}

我需要按键进行合并/聚合,但我并没有完全看到它。

什么是更好或更有效的解决方案?

3 个答案:

答案 0 :(得分:2)

您可以使用setdefault()

In [79]: dic={}
In [80]: for x in lis:
    dic.setdefault(x[0],[]).append(x[1:])
   ....:     
   ....:     

In [82]: dic
Out[82]: {'123': [('abc', 'def'), ('efg', 'hij')], '456': [('klm', 'nop')]}

答案 1 :(得分:2)

一个简单的方法是

from collections import defaultdict

ri = [('123', 'abc', 'def'),('123', 'efg', 'hij'),('456', 'klm','nop')]
response_items = defaultdict(list)
for r in ri:
    response_items[r[0]].append(r[1:])
print response_items

给出了

defaultdict(<type 'list'>, {'123': [('abc', 'def'), ('efg', 'hij')],
                            '456': [('klm', 'nop')]})

如果你想要

defaultdict(<type 'list'>, {'123': ['abc', 'def', 'efg', 'hij'],
                            '456': ['klm', 'nop']})

作为输出,您可以使用response_items[r[0]].extend(r[1:])

答案 2 :(得分:1)

如果有理由使用itertools.groupby,那么您可以避免使用defaultdictsetdefault方法 - [事实上,如果您想沿着这些路线走,那么您真的不需要groupby!] - by:

mydict = {}
for k, g in groupby(some_list, itemgetter(0)):
    mydict[k] = [el[1:] for el in g]
相关问题