Python将字典列表转换为键的dict,值作为列表

时间:2018-01-14 10:00:45

标签: python list dictionary

我有一个对象列表如下:

avariable = [{'id':1,'color':'pink'},{'id':1,'color':'blue'},{'id':2,'color':'green'}]

我想将其转换为:

{
"1" : [{'id':1,'color':'pink'},{'id':1,'color':'blue'}],
"2" : [{'id':2,'color':'green'}]
}

如何实现此输出,请帮助。

2 个答案:

答案 0 :(得分:2)

不使用任何其他库。

avariable = [{'id':1,'color':'pink'},{'id':1,'color':'blue'},{'id':2,'color':'green'}]

new_dict = {}
keys = set([i['id'] for i in avariable])

for key in keys:
    temp = []
    for l in avariable:
        if l['id'] == key:
            temp.append(l)
        new_dict[key] = temp


print(new_dict)
{1: [{'color': 'pink', 'id': 1}, {'color': 'blue', 'id': 1}],
 2: [{'color': 'green', 'id': 2}]}

一个班轮(词典理解):

new_dict = {key: [l for l in avariable if l['id'] == key] for key in set([i['id'] for i in avariable])}       

答案 1 :(得分:1)

正如建议所说,您需要itertools.groupby -

from itertools import groupby

avariable = [{'id':1,'color':'pink'},{'id':1,'color':'blue'},{'id':2,'color':'green'}]
groups = []  
uniquekeys = []  
for k, g in groupby(sorted(avariable, key=lambda x: x['id']), lambda x: x['id']): 
    # Store group iterator as a list 
    groups.append(list(g))        
    uniquekeys.append(k)

print({ str(i):j for i, j in zip(uniquekeys, groups) })

输出 -

{'1': [{'id': 1, 'color': 'pink'}, {'id': 1, 'color': 'blue'}], '2': [{'id': 2,
'color': 'green'}]}