【问题标题】:How to get unique list of values from the list of dictonaries如何从字典列表中获取唯一的值列表
【发布时间】:2021-11-29 17:10:18
【问题描述】:

我有一个这样的 Python 字典列表

test_list = [{'id': 0, 'A':True, 'B':123},
             {'id':76, 'A':True, 'B':73},
             {'id':5, 'A':False, 'B':223},
             {'id':5, 'A':False, 'B':223},
             {'id':85, 'A':True, 'B':4},
             {'id':81, 'A':False, 'B':76},
             {'id':76, 'A':True, 'B':73}]

我想让这个列表独一无二 用简单的set(test_list)给你TypeError: unhashable type: 'dict'

我的以下答案对我来说很好,但我正在寻找一个更好更简短的答案

unique_ids = list(set([x['id'] for x in test_list]))
d = {}
for item in test_list:
    d[item['id']] = item

new_d = []
for x in unique_ids:
    new_d.append(d[x])

【问题讨论】:

  • 由于您的代码有效,在我看来这个问题更适合在Code Review Forum 中提出。 Code Review 是一个针对同行程序员代码审查的问答网站。在发布您的问题之前,请阅读有关如何在本网站上正确提问的相关指南。
  • 看起来很有趣...
  • list({ d["id"] : d for d in test_list}.values())

标签: python list dictionary unique


【解决方案1】:

创建一个新字典,其中键作为 id,值作为整个字典,并且只访问 values

new_d = list({v["id"]: v for v in test_list}.values())

>>> new_d
[{'id': 0, 'A': True, 'B': 123},
 {'id': 76, 'A': True, 'B': 73},
 {'id': 5, 'A': False, 'B': 223},
 {'id': 85, 'A': True, 'B': 4},
 {'id': 81, 'A': False, 'B': 76}]
~~

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多