python - 如何在python中统一一个dict列表

标签 python

我有一个 list :

d = [{'x':1, 'y':2}, {'x':3, 'y':4}, {'x':1, 'y':2}]

{'x':1, 'y':2} 不止一次出现我想从列表中删除它。我的结果应该是:

 d = [{'x':1, 'y':2}, {'x':3, 'y':4} ]

注意: list(set(d)) 在这里不起作用并抛出错误。

最佳答案

如果您的值是可散列的,这将起作用:

>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]

编辑:

我试过没有重复,它似乎工作正常

>>> d = [{'x':1, 'y':2}, {'x':3, 'y':4}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 4, 'x': 3}, {'y': 2, 'x': 1}]

>>> d = [{'x':1,'y':2}]
>>> [dict(y) for y in set(tuple(x.items()) for x in d)]
[{'y': 2, 'x': 1}]

关于python - 如何在python中统一一个dict列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6280978/

相关文章:

python - 文件未在 AWS Elastic Mapreduce 上缓存

python - 基于相似性度量 Pandas 删除数据帧行

python - 如何在 Python 中使用 SQLite 进行基于日期时间的查询?

python - 如何从 DataFrame 列中的对象属性创建列表?

python - django - 如何使用 request.FILES 对发布请求进行单元测试

python - 使用 Flask-SQLAlchemy 实现多对多多数据库连接

python - Django 测试数据库未与自定义测试运行程序一起使用

python - 将整个函数作为字符串获取/并将字符串转换为函数?

python - NumPy 中如何处理大整数?

python - Django DISTINCT 匹配模式与容差