[Python] 딕셔너리 update()

tacowasabii·2024년 6월 13일
0

Python

목록 보기
8/12
post-thumbnail

Python의 딕셔너리에는 update 메서드가 있어 다른 딕셔너리나 키-값 쌍(iterable)에서 키-값 쌍을 업데이트할 수 있다. 이는 주로 두 딕셔너리를 합치거나, 기존 딕셔너리에 새로운 키-값 쌍을 추가하거나 기존 값을 업데이트하는 데 사용된다.


1. 기본 사용법

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로 업데이트되었다.

2. 키-값 쌍 iterable 사용

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 메서드에 전달되어 딕셔너리가 업데이트된다.

3. 키워드 인자 사용

update 메서드는 키워드 인자를 직접 받아 딕셔너리를 업데이트할 수 있다.

my_dict = {'apple': 1, 'banana': 2}

my_dict.update(orange=3, banana=4)
print(my_dict)
# 출력: {'apple': 1, 'banana': 4, 'orange': 3}

이 방법을 사용하면 키워드 인자를 사용하여 간단히 딕셔너리를 업데이트할 수 있다.

4. 여러 방법을 결합하여 사용

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 메서드를 반복해서 호출할 수 있다.

profile
웹 프론트엔드 엔지니어

0개의 댓글

관련 채용 정보