我有多個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)
您的代碼適合我希望實現的功能。謝謝! –