【问题标题】:Getting the latest value of duplicate keys in list of dictionaries获取字典列表中重复键的最新值
【发布时间】:2020-03-12 08:13:17
【问题描述】:

我有一个这样的字典列表 未过滤的字典列表:

[{'team': 'green', 'user': 'bob'}, {'play': '${bla/bla}', 'mentor': 'alice', 'team': 'blue'}, {'team': 'yellow'}]

我需要获得 FILTERED 列表,其中只有最后出现的重复键,例如

过滤列表:

[{'user': 'bob'}, {'play': '${bla/bla}', 'mentor': 'alice'}, {'team': 'yellow'}]

** key 'team' 将只保留一个和最新的值 **

(它可以是任何我事先无法知道的重复键名,所以它应该是通用解决方案)

非常感谢您的帮助!

【问题讨论】:

    标签: python-3.x list dictionary filter duplicates


    【解决方案1】:

    从最后一个字典到第一个字典遍历列表,将所有读取的键保存在一个额外的列表中,如果一个键已经在额外的列表中,则从当前字典中删除它。

    我对 python 不太熟悉,但应该可以:

    myList = [{'team': 'green', 'user': 'bob'}, {'play': '${bla/bla}', 'mentor': 'alice', 'team': 'blue'}, {'team': 'yellow'}]
    myList.reverse()
    delList = []
    for dict in myList:
        for key in list(dict.keys()):
            if key in delList:
                del dict[key]
            else:
                delList.append(key)
    myList.reverse()
    print(myList)
    

    【讨论】:

    • 谢谢!它非常适合我的情况。反向阅读 dict 是一个很好的方法。
    • pL4Gu33,也许你可以澄清一下这个错误 elif isinstance(v, dict): TypeError: isinstance() arg 2 must be a type or tuple of types something is running wrong for my first dict处理,当我运行脚本两次时......
    猜你喜欢
    • 2019-03-18
    • 2019-01-16
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多