Python의 딕셔너리에는 update
메서드가 있어 다른 딕셔너리나 키-값 쌍(iterable)에서 키-값 쌍을 업데이트할 수 있다. 이는 주로 두 딕셔너리를 합치거나, 기존 딕셔너리에 새로운 키-값 쌍을 추가하거나 기존 값을 업데이트하는 데 사용된다.
update
메서드는 다른 딕셔너리나 키-값 쌍의 iterable을 인자로 받아 딕셔너리를 업데이트한다.
my_dict = {'apple': 1, 'banana': 2}
update_dict = {'orange': 3, 'banana': 4}
my_dict.update(update_dict)
print(my_dict)
# 출력: {'apple': 1, 'banana': 4, 'orange': 3}
위의 예에서, update
메서드는 update_dict
의 내용을 my_dict
에 추가하거나, 기존의 값을 업데이트한다. banana
키의 값은 2에서 4로 업데이트되었다.
update
메서드는 iterable 객체(예: 리스트, 튜플)의 키-값 쌍을 인자로 받아 딕셔너리를 업데이트할 수 있다.
my_dict = {'apple': 1, 'banana': 2}
update_items = [('orange', 3), ('banana', 4)]
my_dict.update(update_items)
print(my_dict)
# 출력: {'apple': 1, 'banana': 4, 'orange': 3}
여기서 update_items
는 튜플의 리스트로, update
메서드에 전달되어 딕셔너리가 업데이트된다.
update
메서드는 키워드 인자를 직접 받아 딕셔너리를 업데이트할 수 있다.
my_dict = {'apple': 1, 'banana': 2}
my_dict.update(orange=3, banana=4)
print(my_dict)
# 출력: {'apple': 1, 'banana': 4, 'orange': 3}
이 방법을 사용하면 키워드 인자를 사용하여 간단히 딕셔너리를 업데이트할 수 있다.
update
메서드는 여러 가지 방법을 결합하여 사용할 수도 있다.
my_dict = {'apple': 1, 'banana': 2}
update_dict = {'orange': 3}
update_items = [('pear', 4)]
my_dict.update(update_dict)
my_dict.update(update_items)
my_dict.update(grape=5)
print(my_dict)
# 출력: {'apple': 1, 'banana': 2, 'orange': 3, 'pear': 4, 'grape': 5}
여러 소스로부터 딕셔너리를 업데이트할 때는 update
메서드를 반복해서 호출할 수 있다.