Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

냥집사의 개발일지

Python - 파이썬 기본 문법 정리 (dictionary - 2) 본문

Python

Python - 파이썬 기본 문법 정리 (dictionary - 2)

깅햄찌 2022. 10. 6. 00:06
반응형

안녕하세요 오늘은 저번 포스팅에 이어 dictionary에 대해 정리해보겠습니다.  

 

1. update() 함수로 dictionary 병합하기

friends_dict = {
    "1" : "Jeff",
    "2" : "Alana",
    "3" : "Electra",
}

others_dict = {
    "4" : "John",
    "5" : "Steve"
}

friends_dict.update(others_dict)
print(friends_dict)

friends dictionary에 others dictionary를 update() 함수를 이용해 병합(추가)했습니다. 

아래 결과와 같이 friends_dict에 others의 key,value 값이 추가된 것을 확인할 수 있습니다. 

* update하려는 dictionary들에 key 값이 중복될 경우

friends_dict = {
    "1" : "Jeff",
    "2" : "Alana",
    "3" : "Electra",
}

others_dict = {
    "1" : "John",
    "5" : "Steve"
}

friends_dict.update(others_dict)
print(friends_dict)

update() 함수의 매개변수 즉, 병합되는 dictionary에 key, value값이 우선시됩니다. 

따라서 아래 결과와 같이 1의 value값이 Jeff가 아닌 John임을 확인할 수 있습니다. 

2. dictionary 항목 삭제하기 (del, clear())

friends_dict = {
    "1" : "Jeff",
    "2" : "Alana",
    "3" : "Electra",
}

del friends_dict["1"]
print(friends_dict)

friends_dict.clear()
print(friends_dict)

1) del 구문을 이용하여 dictionary 항목을 삭제합니다. 

    del + dictionary의 key값을 [] 대괄호에 넣어주면 해당 value값이 삭제됩니다. 

2) clear() 함수를 이용하여 dictionary 항목을 전체 삭제합니다.

    dictionary에 clear()함수를 사용하면 모든 항목이 삭제됩니다. 

오늘은 저번 포스팅에 이어 dictionary에 대해 정리해보았습니다.  

오늘 회식을 길게해서.. 너무 힘드네요..

다음 포스팅에서도 dictionary에 대해 더 알아보아요~

Comments