【发布时间】:2016-03-28 07:56:18
【问题描述】:
我对 python 非常陌生。
我有一个充满 json 对象的数组。一些 json 对象包含重复的值。数组如下所示:
[{"id":"1","name":"Paul","age":"21"},
{"id":"2","name":"Peter","age":"22"},
{"id":"3","name":"Paul","age":"23"}]
如果name 与另一个json 对象相同,我要做的是删除一个项目,并将第一个保留在数组中。
所以在这种情况下我应该留下
[{"id":"1"."name":"Paul","age":"21"},
{"id":"2","name":"Peter","age":"22"}]
我目前拥有的代码如下所示,主要是based on this answer:
import json
ds = json.loads('python.json') #this file contains the json
unique_stuff = { each['name'] : each for each in ds }.values()
all_ids = [ each['name'] for each in ds ]
unique_stuff = [ ds[ all_ids.index(text) ] for text in set(texts) ]
print unique_stuff
我什至不确定这条线在ds = json.loads('python.json') #this file contains the json 是否正常工作,就像我尝试和print ds 一样,控制台中没有显示任何内容。
【问题讨论】:
-
请向我们展示您的无效代码,以便我们帮助您修复它。
-
@PM2Ring 我更新了我上面的问题
标签: python python-2.7