Common /Python

[Python] Dictionary 값 수정, 추가, 삭제

언덕너머에 2017. 7. 2. 14:19

Dictionary 값 수정

리스트와 마찮가지로 해당 key의 value를 변경해주면 된다.

ex)


dict = { 'one' : 0, 'two' : 2 }

dict['one'] = 1


Dictionary 추가

리스트와는 달리 Dictionary변수에 key와 value를 추가하면 된다.

ex)
dict = { 'one' : 1, 'two' : 2 }
dict['three'] = 3


Dictionary 삭제

리스트와 삭제방법이 동일하다. 아래와 같이 사용하면 된다.

ex1)


dict = { 'one' : 1, 'two' : 2, 'three' : 3 }

del(dict['one'])


* del 대신에 pop을 사용할 수도 있다. pop을 사용하면 삭제와 동시에 삭제된 값을 반환한다.

ex2)


dict.pop('one')

1


Dictionnary 결합

두 개의 Dictionary를 결합하는 방법은 아래와 같다.

ex)


dic1 = {1:10, 2:20}

dic2 = {1:100, 3:300}

dic1.update(dic2)

print(dic1)


결과

{1: 100, 2: 20, 3: 300}


예제 소스

dict = { 'one' : 0, 'two' : 2 }


dict['one'] = 1

print(dict)


dict['three'] = 3

print(dict)


del(dict['one'])

print(dict)


dict.pop('two')

print(dict)

{'one': 1, 'two': 2}

{'one': 1, 'two': 2, 'three': 3}

{'two': 2, 'three': 3}

{'three': 3}