我有多个JSON文件,其中包含大写和国家。如何从所有文件中删除重复的键值对?如何从多个JSON文件中删除重复内容?
我有以下的JSON文件之一
{
"data": [
{
"Capital": "Berlin",
"Country": "Germany"
},
{
"Capital": "New Delhi",
"Country": "India"
},
{
"Capital": "Canberra",
"Country": "Australia"
},
{
"Capital": "Beijing.",
"Country": "China"
},
{
"Capital": "Tokyo",
"Country": "Japan"
},
{
"Capital": "Tokyo",
"Country": "Japan"
},
{
"Capital": "Berlin",
"Country": "Germany"
},
{
"Capital": "Moscow",
"Country": "Russia"
},
{
"Capital": "New Delhi",
"Country": "India"
},
{
"Capital": "Ottawa",
"Country": "Canada"
}
]
}
有包含许多这样的JSON文件重复items.How做我删除repetitve项目只保留第一次出现?我已经试过这一点,但没有按不工作
dupes = []
for f in json_files:
with open(f) as json_data:
nations = json.load(json_data)['data']
#takes care of duplicates and stores it in dupes
dupes.append(x for x in nations if x['Capital'] in seen or seen.add(x['Capital']))
nations = [x for x in nations if x not in dupes] #want to keep the first occurance of the item present in dupes
with open(f, 'w') as json_data:
json.dump({'data': nations}, json_data)
您的代码适合我希望实现的功能。谢谢! –