简体   繁体   English

在字典列表中,根据键合并列表

[英]inside list of dictionaries, merge lists based on key

I have nested dictionaries in a list of dictionaries, I want to merge the lists based on 'id'我在字典列表中嵌套了字典,我想根据'id'合并列表

res = [{'i': ['1'], 'id': '123'},
       {'i': ['1'], 'id': '123'},
       {'i': ['1','2','3','4','5','6'],'id': '123'},
       {'i': ['1'], 'id': '234'},
       {'i': ['1','2','3','4','5'],'id': '234'}]

Desired output:所需的 output:

[{'i': [1, 1, 1, 2, 3, 4, 5, 6], 'id': '123'},
 {'i': [1, 1, 2, 3, 4, 5], 'id': '234'}]

I am trying to merge the nested dictionaries based on key "id" .我正在尝试根据键"id"合并嵌套字典。 I couldn't figure out the best way out:我想不出最好的出路:

import collections
d = collections.defaultdict(list)
for i in res:
    for k, v in i.items():
        d[k].extend(v)

The above code is merging all the lists, but i wantto merge lists based on key "id".上面的代码正在合并所有列表,但我想根据键“id”合并列表。

Something like this should do the trick这样的事情应该可以解决问题

from collections import defaultdict

merged = defaultdict(list)
for r in res:
    merged[r['id']].extend(r['i'])

output = [{'id': key, 'i': merged_list} for key, merged_list in merged.items()]

The following produces the desired output, using itertools.groupby :以下使用itertools.groupby生成所需的 output:

from operator import itemgetter
from itertools import groupby

k = itemgetter('id')

[
    {'id': k, 'i': [x for d in g for x in d['i']]} 
    for k, g in groupby(sorted(res, key=k), key=k)
]

I'm not sure what the expected behavior should be when there are duplicates -- for example, should the lists be:我不确定当有重复时预期的行为应该是什么——例如,列表应该是:

  • treated like a set() ?set()一样对待?
  • appended, and there could be multiple items, such as [1,1,2,3...] ?附加,并且可能有多个项目,例如[1,1,2,3...]
  • doesn't matter -- just take any没关系——随便拿

Here would be one variation where we use a dict comprehension :这是我们使用dict comprehension的一种变体:

{item['id']: item for item in res}.values()
# [{'i': ['1', '2', '3', '4', '5'], 'id': '234'}, {'i': ['1', '2', '3', '4', '5', '6'], 'id': '123'}]

If you provide a bit more information in your question, I can update the answer accordingly.如果您在问题中提供更多信息,我可以相应地更新答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM