logo

파이썬 | 두 개의 사전 병합

Python에서 사전은 사전의 값에 액세스하는 데 키가 사용되는 키-값 쌍의 요소를 포함하는 데이터 구조입니다. 파이썬 defaultdict와 같은 내장 사전이 있습니다. 이 기사에서는 두 개의 사전을 병합하는 다양한 방법을 살펴보겠습니다.



  Input:   dict1 = {'a': 10, 'b': 8}  dict2 = {'d': 6, 'c': 4}   Output:   {'a': 10, 'b': 8, 'd': 6, 'c': 4}>

Python에서 두 사전 병합

그 방법은 다양하다 사전 Python의 다양한 함수와 생성자를 사용하여 병합할 수 있습니다. 다음은 다음과 같은 몇 가지 방법입니다.

  • 사용 업데이트()
  • 사용 포장 풀기 연산자
  • 병합 사용 | 운영자
  • 루프 사용 및 키() 방법
  • dict 생성자 사용
  • 합집합 연산자(|)와 함께 dict() 생성자 사용
  • 사용 줄이다()

파이썬 업데이트()

방법을 사용하여 업데이트() Python에서는 하나의 목록을 다른 목록에 병합할 수 있습니다. 하지만 여기서는 두 번째 목록이 첫 번째 목록에 병합되고 새 목록이 생성되지 않습니다. 그것은 반환 없음 . 이 예에서는 업데이트 기능을 사용하여 두 개의 사전을 병합합니다.

파이썬
# Python code to merge dict using update() method def Merge(dict1, dict2): return(dict2.update(dict1)) # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # This returns None print(Merge(dict1, dict2)) # changes made in dict2 print(dict2)>

산출:



None {'c': 4, 'a': 10, 'b': 8, 'd': 6}>

시간 복잡도: 에)
보조 공간: 오(1)

Python 압축 풀기 연산자

** [이중 별표]를 사용하는 것은 사전을 사용하여 함수에 직접 여러 인수를 전달할 수 있는 지름길입니다. 자세한 내용은 다음을 참조하세요. **파이썬의 kwargs . 이를 사용하여 먼저 첫 번째 사전의 모든 요소를 ​​세 번째 사전에 전달한 다음 두 번째 사전을 세 번째 사전에 전달합니다. 그러면 첫 번째 사전의 중복 키가 대체됩니다.

파이썬
# Python code to merge dict using a single  # expression def Merge(dict1, dict2): res = {**dict1, **dict2} return res # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} dict3 = Merge(dict1, dict2) print(dict3)>

산출
{'a': 10, 'b': 8, 'd': 6, 'c': 4}>

시간 복잡도: 오(1)
보조 복잡성: 에)



Python 병합 사전 사용 | 파이썬 3.9에서

Python의 최신 업데이트에서는 이제 |를 사용할 수 있습니다. 두 개의 사전을 병합하는 연산자입니다. 사전을 병합하는 것은 매우 편리한 방법입니다. 이 예에서는 | 두 개의 사전을 병합하는 연산자입니다.

파이썬
# code # Python code to merge dict using a single  # expression  def Merge(dict1, dict2): res = dict1 | dict2 return res # Driver code  dict1 = {'x': 10, 'y': 8} dict2 = {'a': 6, 'b': 4} dict3 = Merge(dict1, dict2) print(dict3) # This code is contributed by virentanti16>

산출:

{'x': 10, 'a': 6, 'b': 4, 'y': 8}>

시간 복잡도: 오(1)
보조 공간: 에)

for 루프 및key() 메소드 사용

이 예에서는 루프와 열쇠() 두 개의 사전을 병합하는 방법.

파이썬
# code # Python code to merge dictionary def Merge(dict1, dict2): for i in dict2.keys(): dict1[i]=dict2[i] return dict1 # Driver code dict1 = {'x': 10, 'y': 8} dict2 = {'a': 6, 'b': 4} dict3 = Merge(dict1, dict2) print(dict3) # This code is contributed by Bhavya Koganti>

산출
{'x': 10, 'y': 8, 'a': 6, 'b': 4}>

ChainMap 클래스를 사용하는 Python 병합 사전

이 예에서는 내장된 함수를 사용하여 Python에서 사전을 병합합니다. 체인맵 의 수업 컬렉션 기준 치수. 이 클래스를 사용하면 여러 사전의 단일 보기를 만들 수 있으며 ChainMap에 대한 모든 업데이트나 변경 사항은 기본 사전에 반영됩니다.

파이썬
from collections import ChainMap # create the dictionaries to be merged dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} # create a ChainMap with the dictionaries as elements merged_dict = ChainMap(dict1, dict2) # access and modify elements in the merged dictionary print(merged_dict['a']) # prints 1 print(merged_dict['c']) # prints 3 merged_dict['c'] = 5 # updates value in dict2 print(merged_dict['c']) # prints 5 # add a new key-value pair to the merged dictionary merged_dict['e'] = 6 # updates dict1 print(merged_dict['e']) # prints 6>

산출
1 3 5 6>

dict 생성자를 사용하여 Python에서 두 사전을 병합합니다.

이 예에서는 dict 생성자를 사용하여 두 개의 사전을 병합합니다.

파이썬
def merge_dictionaries(dict1, dict2): merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict # Driver code dict1 = {'x': 10, 'y': 8} dict2 = {'a': 6, 'b': 4} print(merge_dictionaries(dict1, dict2))>

산출
{'x': 10, 'y': 8, 'a': 6, 'b': 4}>

시간 복잡도: 에)
보조 공간: 에)

dict() 생성자와 결합 연산자(|)를 사용하는 Python 병합 사전

이 메서드는 결합 연산자(|)와 함께 dict() 생성자를 사용하여 두 개의 사전을 병합합니다. 합집합 연산자는 두 사전의 키와 값을 결합하며, 두 사전의 공통 키는 두 번째 사전의 값을 가져옵니다.

파이썬
# method to merge two dictionaries using the dict() constructor with the union operator (|) def Merge(dict1, dict2): # create a new dictionary by merging the items of the two dictionaries using the union operator (|) merged_dict = dict(dict1.items() | dict2.items()) # return the merged dictionary return merged_dict # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # merge the two dictionaries using the Merge() function merged_dict = Merge(dict1, dict2) # print the merged dictionary print(merged_dict)>

산출
{'d': 6, 'b': 8, 'c': 4, 'a': 10}>

시간 복잡도: O(n), 여기서 n은 두 사전의 총 키-값 쌍 수입니다.
보조 공간: O(n), 여기서 n은 두 사전의 총 키-값 쌍 수입니다.

Python은 Reduce()를 사용하여 두 개의 사전을 병합합니다.

이 예에서는 Reduce() 함수를 사용하여 두 개의 사전을 병합합니다. 이 방법에서는 병합 함수를 정의한 다음 두 개의 사전을 인수로 사용하여 병합을 반환합니다.

파이썬
from functools import reduce def merge_dictionaries(dict1, dict2): merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} dict_list = [dict1, dict2] # Put the dictionaries into a list result_dict = reduce(merge_dictionaries, dict_list) print(result_dict) #This code is contributed by Rayudu.>

산출
{'a': 10, 'b': 8, 'd': 6, 'c': 4}>

시간 복잡도 : O(n), 여기서 n은 dict_list 목록의 사전 수입니다.
보조 복잡도 : O(m), 여기서 m은 모든 사전에 있는 키-값 쌍의 총 개수입니다.