Python - 根据 JSON 中的值从 JSON 中删除重复元素

标签 python json duplicates

我有一个 JSON 对象,其中可能包含重复的项目和位置,并且我想保留风险最高的项目和位置(并且仅保留其中一个)

[{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Low'
#Other values are omitted
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Moderate'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'
}]

我尝试将其转换为 pandas 数据帧,根据risk_level对其进行排序并使用 drop_duplicates 但这会导致 JSON 中其他值出现问题(例如,将 None 转换为 NaN、将 int 转换为 float 等),所以我不这样做认为可行。

    #Convert to dataframe and drop identical insights with lowest severities
    dfInsights = pd.DataFrame(response['data'])
    dfInsights = dfInsights.reindex(columns=list(response['data'][0].keys()))
    dfInsights.sort_values(['risk_level'], inplace=True)
    dfInsights.drop_duplicates(['item','location'], keep='first', inplace=True)
    dfToJSON = dfInsights.to_dict(orient='records')

我希望结果是:

[{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'
}]

最佳答案

您可以利用 itertools.groupby 以及基于权重的自定义键函数:

d = [{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Low'
#Other values are omitted
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'Moderate'
},
{
'item': 'itemone',
'location': 'locationone',
'risk_level': 'High'
},
{
'item': 'itemtwo',
'location': 'locationtwo',
'risk_level': 'Low'
}]

from itertools import groupby
from operator import itemgetter

f = itemgetter('item', 'location')
weights = {'Low':2, 'Moderate':1, 'High':0}

out = []
for v, g in groupby(sorted(d, key=lambda k: (f(k), weights[k['risk_level']])), key=f):
    out.append(next(g))

from pprint import pprint
pprint(out, width=30)

打印:

[{'item': 'itemone',
  'location': 'locationone',
  'risk_level': 'High'},
 {'item': 'itemtwo',
  'location': 'locationtwo',
  'risk_level': 'Low'}]

关于Python - 根据 JSON 中的值从 JSON 中删除重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57086666/

相关文章:

python - 如何修复OpenCV Numpy错误,对象不可迭代

php - 在 PHP 中检查字符串是否为 JSON 的最快方法?

ruby-on-rails - 通过 JSON/XML 将二进制数据发送到 (Rails) RESTful 端点?

sql - 删除SQL中除第一条记录外的重复记录

php - key 2 的重复条目 ''

python - 在 matplotlib 注释中格式化数学文本

python - 具有多个查找参数的 django-rest-framework HyperlinkedIdentityField

json - 在 Azure JSON 模板中创建 CustomScript 的正确方法

text - 从文本 Notepad++ 中删除两个重复项(原始和重复)

java - 我怎样才能在java中实现zlib.compress