본문 바로가기
Programming Study

[파이썬 python] dictionary(딕셔너리) 요소 추가 / 삭제 / 변경 / 병합 / 초기화

by White,,JY 2021. 9. 8.
728x90
300x250
딕셔너리 선언
dict = {'key' : 'value'}
dict2 = {1: 'abc'}
dict3 = {'hello' : ['w', 'o', 'r', 'l', 'd']}

 

딕셔너리 요소 추가
a = {1: 'a'}
a[3] = {'c'}
print(a)
-> {1: 'a', 3: 'c'}
a['hello'] = ['w', 'o', 'r', 'l', 'd']
print(a)
-> {1: 'a', 3: 'c', 'hello' : ['w', 'o', 'r', 'l', 'd']}
300x250
딕셔너리 요소 삭제
a = {1: 'a', 3: 'c', 'hello' : ['w', 'o', 'r', 'l', 'd']}
del a[1]
print(a)
-> {3: 'c', 'hello' : ['w', 'o', 'r', 'l', 'd']}
a.pop(3)
print(a)
-> {'hello' : ['w', 'o', 'r', 'l', 'd']}

 

딕셔너리 value 변경
a = {3: 'c', 'hello' : ['w', 'o', 'r', 'l', 'd']}
a[3] = 'abc'
print(a)
-> {3: 'abc', 'hello' : ['w', 'o', 'r', 'l', 'd']}

 

딕셔너리 병합
dict = {'key' : 'value'}
dict2 = {1: 'abc'}
dict.update(dict2)
print(dict)
-> {'key' : 'value', 1: 'abc'}

 

딕셔너리 초기화
a = {3: 'c', 'hello' : ['w', 'o', 'r', 'l', 'd']}
a.clear()
print(a)
-> {}
728x90
300x250