python-从json对象中选择唯一键值 [英] python-select unique key values from json object
问题描述
我有一个 json 回复:
{
"data": [
{
"id": "1",
"name": "Tom",
"age": "24",
},
{
"id": "2",
"name": "Nick",
"age": "45",
},
{
"id": "3",
"name": "Harry",
"age": "18",
},
{
"id": "1",
"name": "Tom",
"age": "29",
}
],
"count": 4
}
我希望输出像这样:
output[
{
"id": "1",
"name": "Tom",
"age": "24",
},
{
"id": "2",
"name": "Nick",
"age": "45",
},
{
"id": "3",
"name": "Harry",
"age": "18",
}
]
我想要的是获取所有具有唯一名称的字典对象.
我知道如何获取唯一名称,但是我也想获取id
和age
.
有两个对应于name
Tom
的字典对象.我想在输出中保留一个.
What I want is to fetch all dictionary objects having unique names.
I know how to fetch unique names, but I want to fetch id
and age
too.
There are two dictionary objects corresponding to name
Tom
. I want to keep one in my output.
这是用于获取唯一名称的工作代码:
size=len(data["data"])
uniqueNames = [];
for i in range(0,size,1):
if(data["data"][i]["name"] not in uniqueNames):
uniqueNames.append(data["data"][i]["name"]);
print uniqueNames
推荐答案
在这里,您应该修改代码:只需保留名称注册表,然后添加一个算法即可保留其余信息.对我来说,我创建了另一个数组来存储具有唯一名称的整个数据对象,这些名称称为returnValue.只要有一个唯一的名称,它就会将整个数据对象推送到returnValue上.然后,将其打印出来(如果将其转换为函数,则将其返回).
Here's how you should fix your code: Simply keep your registry of names and then add a algorithm for keeping the rest of the information. For me, I created another array for storing the whole data object that have unique names, called returnValue. And whenever there is a unique name, it pushes the entire data object onto returnValue. Then, it prints it out (or returns it, if you turn it into a function).
returnValue = []
size=len(data["data"])
uniqueNames = []
for i in range(0,size,1):
if(data["data"][i]["name"] not in uniqueNames):
uniqueNames.append(data["data"][i]["name"])
returnValue.append(data["data"][i])
print returnValue
由于作者的问题:
returnValue = []
badValues = []
size=len(data["data"])
uniqueNames = []
for i in range(0,size,1):
if(data["data"][i]["name"] not in uniqueNames):
uniqueNames.append(data["data"][i]["name"])
returnValue.append(data["data"][i])
else:
badValues.append(data["data"][i])
print "Good ones: "
print returnValue
print "Bad ones: "
print badValues
这篇关于python-从json对象中选择唯一键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!