简体   繁体   English

json 对象列表的唯一值

[英]Unique values of list of json objects

I have a huge list of json objects, and many of them are repeated.我有一个巨大的 json 对象列表,其中许多是重复的。 Those that are repeated have exactly the same values for the same keys.那些重复的对于相同的键具有完全相同的值。 For example in the following list例如在下面的列表中

[{ "name": "John", "id": 1},{ "name": "Carl", "id": 5},{ "name": "John", "id": 1}]

I want to get the unique objects我想获得独特的对象

[{ "name": "John", "id": 1},{ "name": "Carl", "id": 5}]

I tried using the function set() but apparently it does not work with elements of type: dict.我尝试使用函数 set() 但显然它不适用于以下类型的元素:dict。

Is there any efficient way of doing this?有没有什么有效的方法可以做到这一点?

Thanks in advance提前致谢

Try hashing the dictionaries before adding them to your set.在将它们添加到您的集合之前尝试对字典进行哈希处理。 To do this, simply turn the dictionary into a string.为此,只需将字典转换为字符串即可。

d1 = { "name": "John", "id": 1}
d2 = { "name": "Carl", "id": 5}
d3 = { "name": "John", "id": 1}
s = set()

for d in [d1,d2,d3]:
    if str(d) not in s:
        s.add(str(d))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM