猿问

合并 id 重复的字典列表 - python3

我有一个字典列表:


[{"id":"1", "name":"Alice", "age":"25", "languages":"German"},

 {"id":"1", "name":"Alice", "age":"25", "languages":"French"},

 {"id":"2", "name":"John", "age":"30", "languages":"English"},

 {"id":"2", "name":"John", "age":"30", "languages":"Spanish"}]

我希望最终结果是(我在检查重复项时只考虑 id):


[{"id":"1", "name":"Alice", "age":"25", "languages":"German, French"},

 {"id":"2", "name":"John", "age":"30", "languages":"English, Spanish"}]

看着类似的问题,我认为使用集合可能是答案,但无法正确实现。


提前感谢您的回答。


芜湖不芜
浏览 147回答 1
1回答

海绵宝宝撒

在这里有点冗长以帮助查看结构。绝对可以做一些很酷的 lambda 东西来解决这个问题,并使列表理解更加“pythonic”。但这里有一个快速的解决方案!# Set up initial dataunmerged = [    {"id":"1", "name":"Alice", "age":"25", "languages":"German"},    {"id":"1", "name":"Alice", "age":"25", "languages":"French"},    {"id":"2", "name":"John", "age":"30", "languages":"English"},    {"id":"2", "name":"John", "age":"30", "languages":"Spanish"}]# merge the data by your composite key of id-name-agemerged = {}for entry in unmerged:    entry_id = entry['id']    entry_name = entry['name']    entry_age = entry['age']    entry_languages = entry['languages']    composite_key = entry_id + entry_name + entry_age    if composite_key in merged:        merged[composite_key]['languages'].append(entry_languages)    else:        merged[composite_key] = {            'id': entry_id,            'name': entry_name,            'age': entry_age,            'languages': [entry_languages]        }# reconstruct your list with just your unique entriescleaned = []for key, value in merged.items():    print(key, value)    cleaned.append({        'id': value['id'],        'name': value['name'],        'age': value['age'],        'languages': ', '.join(value['languages']) # string join langauges by ", "    })for clean in cleaned:    print(clean)然后为您提供最终输出,其中清理的是您的合并条目列表:{'id': '1', 'name': 'Alice', 'age': '25', 'languages': 'German, French'}{'id': '2', 'name': 'John', 'age': '30', 'languages': 'English, Spanish'}谢谢,如果这有帮助,请告诉我!
随时随地看视频慕课网APP

相关分类

Python
我要回答