如果值重复,则从数组中删除 json 项 python [英] removing json items from array if value is duplicate python

查看:27
本文介绍了如果值重复,则从数组中删除 json 项 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 非常陌生.

I am incredibly new to python.

我有一个充满 json 对象的数组.一些 json 对象包含重复值.数组如下所示:

I have an array full of json objects. Some of the json objects contain duplicated values. The array looks like this:

 [{"id":"1","name":"Paul","age":"21"},
  {"id":"2","name":"Peter","age":"22"},
  {"id":"3","name":"Paul","age":"23"}]

如果 name 与另一个 json 对象相同,我想要做的是删除一个项目,并将第一个留在数组中.

What I am trying to do is to remove an item if the name is the same as another json object, and leave the first one in the array.

所以在这种情况下我应该留下

So in this case I should be left with

  [{"id":"1"."name":"Paul","age":"21"},
  {"id":"2","name":"Peter","age":"22"}]

我目前拥有的代码可以在下面看到,主要是基于这个答案:

The code I currently have can be seen below and is largely 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 控制台中什么也没有显示.

I am not even sure that this line is working ds = json.loads('python.json') #this file contains the json as when I try and print ds nothing shows up in the console.

推荐答案

首先,您的 json 代码段格式无效 - 某些键用点代替逗号分隔.

First of all, your json snippet has invalid format - there are dot instead of commas separating some keys.

您可以使用以名称为键的字典来解决您的问题:

You can solve your problem using a dictionary with names as keys:

import json

with open('python.json') as fp:
    ds = json.load(fp) #this file contains the json

    mem = {}

    for record in ds:
        name = record["name"]
        if name not in mem:
            mem[name] = record

    print mem.values()

这篇关于如果值重复,则从数组中删除 json 项 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆