대문자와 국가를 포함하는 여러 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 항목을 제거 할 경우에만 이를 선두? 나는이 시도했지만 아무튼있다 '이 t은
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)
코드는 내가 달성하기를 바랄만큼 잘 작동합니다. 감사합니다! –