Python:将字典中的列表项分组 [英] Python: group list items in a dict

查看:35
本文介绍了Python:将字典中的列表项分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字典列表中生成一个字典,按某个键的值对列表项进行分组,例如:

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)

另一个使用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 ?

是否有更多 Pythonic/concise 或性能更好的方法来实现这一目标?

Is there any more pythonic/concise or better performing way of achieving this ?

推荐答案

您想根据列表元素的 'a' 键的值对输入列表进行分组是否正确?如果是这样,你的第一种方法是最好的,一个小的改进,使用 dict.setdefault:

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:将字典中的列表项分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆