Python:一个dict中的组列表项 [英] Python: group list items in a dict
问题描述
input_list = [
{'a':'tata','b':'foo'},
{'a':'pipo','b' :'titi'},
{'a':'pipo','b':'toto'},
{'a':'tata','b':'bar'}
]
output_dict = {
'pipo':[
{'a':'pipo','b':'titi'},
{'a' :'pipo','b':'toto'}
],
'tata':[
{'a':'tata','b':'foo'},
{'a':'tata','b':'bar'}
]
}
到目前为止,我发现了两种方法。第一个简单地遍历列表,在dict中为每个键值创建子列表,并将与这些键匹配的元素附加到子列表中:
l = [
{'a':'tata','b':'foo'},
{'a':'pipo','b':'titi'},
{'a':'pipo','b':'toto'},
{'a':'tata','b':'bar'}
]
res = {}
对于e中的e:
res [e ['a']] = res.get(e ['a'],[])
res [e ['a']]。append(e)
另一个使用 itertools.groupby
:
import itertools
from operator import itemgetter
l = [
{'a':'tata','b':'foo'},
{'a':'pipo','b' 'b $ b'''''''',
{'a':'tata','b':'bar'}
]
l = sorted(l,key = itemgetter('a'))
res = dic t((k,list(g))for k,g in itertools.groupby(l,key = itemgetter('a')))
我不知道哪个替代方案是最有效的?
有没有更多的pythonic /简洁或更好的表现方式实现这一点? / p>
是否正确,您希望将列表元素的a键的值分组到输入列表?如果是这样,你的第一种方法是最好的,一个小的改进,使用dict.setdefault:
res = {}
for item in l:
res.setdefault(item ['a'],[])。append(item)
I want to generate a dictionary from a list of dictionaries, grouping list items by the value of some key, such as:
input_list = [
{'a':'tata', 'b': 'foo'},
{'a':'pipo', 'b': 'titi'},
{'a':'pipo', 'b': 'toto'},
{'a':'tata', 'b': 'bar'}
]
output_dict = {
'pipo': [
{'a': 'pipo', 'b': 'titi'},
{'a': 'pipo', 'b': 'toto'}
],
'tata': [
{'a': 'tata', 'b': 'foo'},
{'a': 'tata', 'b': 'bar'}
]
}
So far I've found two ways of doing this. The first simply iterates over the list, create sublists in the dict for each key value and append elements matching these keys to the sublist :
l = [
{'a':'tata', 'b': 'foo'},
{'a':'pipo', 'b': 'titi'},
{'a':'pipo', 'b': 'toto'},
{'a':'tata', 'b': 'bar'}
]
res = {}
for e in l:
res[e['a']] = res.get(e['a'], [])
res[e['a']].append(e)
And another using itertools.groupby
:
import itertools
from operator import itemgetter
l = [
{'a':'tata', 'b': 'foo'},
{'a':'pipo', 'b': 'titi'},
{'a':'pipo', 'b': 'toto'},
{'a':'tata', 'b': 'bar'}
]
l = sorted(l, key=itemgetter('a'))
res = dict((k, list(g)) for k, g in itertools.groupby(l, key=itemgetter('a')))
I wonder which alternative is the most efficient ?
Is there any more pythonic/concise or better performing way of achieving this ?
Is it correct that you want to group your input list by the value of the 'a' key of the list elements? If so, your first approach is the best, one minor improvement, use dict.setdefault:
res = {}
for item in l:
res.setdefault(item['a'], []).append(item)
这篇关于Python:一个dict中的组列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!