相关疑难解决方法(0)

Python: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'}
         ]
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经找到了两种方法.第一个简单地遍历列表,在dict中为每个键值创建子列表,并将匹配这些键的元素附加到子列表:

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)
Run Code Online (Sandbox Code Playgroud)

而另一个使用itertools.groupby:

import itertools
from operator import …
Run Code Online (Sandbox Code Playgroud)

python algorithm dictionary group-by

13
推荐指数
3
解决办法
5673
查看次数

标签 统计

algorithm ×1

dictionary ×1

group-by ×1

python ×1