2017-10-17 2 views
3

대문자와 국가를 포함하는 여러 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) 

답변

1

목록 함축이 좋은 일! 하지만 ... if 진술서가있을 때 코드를 복잡하게 만들 수 있습니다.

이것은 어쨌든 의 어법입니다. 오히려 목록 작성을 자주 사용하는 것이 좋습니다. 이 특별한 경우에는 더 많은 확산 솔루션이 더 읽기 쉽습니다.

나의 제안은 이것이다 :

import json 

seen = [] 
result = [] 

with open('data.json') as json_data: 
    nations = json.load(json_data)['data'] 
    #takes care of duplicates and stores it in dupes 
    for item in nations: 
     if item['Capital'] not in seen: 
      seen.append(item['Capital']) 
      result.append(item) 

with open('data.no_dup.json', 'w') as json_data: 
    json.dump({'data': result}, json_data) 

는 테스트 및 파이썬 3.5.2에서 작동합니다.

편의를 위해 외부 루프를 제거했음을 유의하십시오. 다음

+0

코드는 내가 달성하기를 바랄만큼 잘 작동합니다. 감사합니다! –

0

당신이 당신의 주어진 JSON이 달성 할 수있는 방법의 샘플 코드

import json 

files = ['countries.json'] 

for f in files: 
    with open(f,'r') as fp: 
     nations = json.load(fp) 
    result = [dict(tupleized) for tupleized in set(tuple(item.items())\ 
      for item in nations['data'])] 
print result 
print len(result) 

출력 :

[{u'Country': u'Russia', u'Capital': u'Moscow'}, {u'Country': u'Japan', u'Capital': u'Tokyo'}, {u'Country': u'Canada', u'Capital': u'Ottawa'}, {u'Country': u'India', u'Capital': u'New Delhi'}, {u'Country': u'Germany', u'Capital': u'Berlin'}, {u'Country': u'Australia', u'Capital': u'Canberra'}, {u'Country': u'China', u'Capital': u'Beijing.'}] 
7 
+0

이렇게하면 '{'Country ':'Russia ','Capital ':'Moscow '}'및'{ 'Country': 'Zaire', 'Capital': 'Moscow'}와 같은 중복 쌍만 필터링 할 수 있습니다. '모두 '결과'에 나타납니다 – jpyams

2

당신은 아마 멋진 지능형리스트를 사용할 수 없지만 일반 루프해야 work

used_nations = {} 
for nation in nations: 
    if nation['Capital'] in used_nations: 
     nations.remove(nation) 
    else: 
     used_nations.add(nation['Capital']) 
+0

이것은 JS가 아니며 'nation.country'는 작동하지 않습니다. – nutmeg64

+0

@ nutmeg64 누군가는 오래 전에'python.js'를 만들 것이라고 확신합니다.) – jpyams

관련 문제