Articles

Affichage des articles du janvier, 2018

[Python] 2개 딕셔너리 합치기 + about ' itertools '

파이썬의 두 딕셔너리를 하나로 합할 수 있을까? 있다. 방법 1 : update([대상]) update() 함수를 사용하면, 기준 딕셔너리의 키/값 쌍이 대상의 키/값 쌍으로 업데이트되고, none 이 반환된다.  대상은 딕셔너리 객체일 수도 있고, 키/값 쌍일 수도 있다.  예를 들면, dict1 과 dict2가 있다고 할 때, dict2.update(dict1) 을 하면, update는 none을 반환하고 dict2에는 dict1이 덮어씌워진다.  중복된 것은 dict1의 것으로 대체된다. 또, dict.update(1=one, 2=two) 처럼 할 수도 있다. 방법 2: print dict(dict2, **dict1) 이 경우에는 dict1이 dict2를 덮어 쓴다. ** 주의해야 할 것은, 중복된 쌍이 바뀌기 때문에 위 방법들은 키 값이 변해도 상관 없을 때 쓰자. 그럼, 두 딕셔너리의 키/값을 모두 유지하면서 병합하려면? 조금 복잡하지만 아래와 같이 하면 된다. 퍼왔다. 지우라고 하면 지운다. ( by  Abder-Rahman Ali ) from itertools import chain from collections import defaultdict dict1 = { 'bookA' : 1 , 'bookB' : 2 , 'bookC' : 3 } dict2 = { 'bookC' : 2 , 'bookD' : 4 , 'bookE' : 5 } dict3 = defaultdict( list ) for k, v in chain(dict1.items(), dict2.items()):      dict3[k].append(v) for k, v in dict3.items():      print (k, v) 결과는 ( 'bookA...