为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

芜湖不芜 2022-07-26 21:55:52
我有一个字典列表:[{"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"}]看着类似的问题,我认为使用集合可能是答案,但无法正确实现。提前感谢您的回答。
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

在这里有点冗长以帮助查看结构。绝对可以做一些很酷的 lambda 东西来解决这个问题,并使列表理解更加“pythonic”。但这里有一个快速的解决方案!


# Set up initial data

unmerged = [

    {"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-age

merged = {}

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 entries

cleaned = []

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'}

谢谢,如果这有帮助,请告诉我!


查看完整回答
反对 回复 2022-07-26
  • 1 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信