Python 사전 update() 메서드

Python 사전 update() 메서드 다른 사전 객체 또는 반복 가능한 키/값 쌍의 요소로 사전을 업데이트합니다.

예:

  Original dictionary :   {'A': 'Geeks', 'B': 'For'}   Updated dictionary :   {'A': 'Geeks', 'B': 'Geeks'}    Original dictionary :   {'A': 'Geeks', 'B': 'For'}   Updated dictionary :   {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} 

Python 사전 업데이트 방법의 구문

사전 update() 메소드 파이썬 다음과 같은 구문이 있습니다.

통사론: dict.update([기타])

매개변수: 이 메서드는 사전이나 키/값 쌍(일반적으로 튜플)의 반복 가능한 개체를 매개 변수로 사용합니다.

보고: 값을 반환하지 않지만 사전 개체 또는 키/값 쌍의 반복 가능한 개체의 요소로 사전을 업데이트합니다.

Python 사전 update() 예

데이터를 업데이트하는 update() 메서드의 몇 가지 예를 살펴보겠습니다. 파이썬 사전 .

다른 사전으로 업데이트

여기서는 update() 메서드를 사용하여 Python에서 사전을 업데이트하고 다른 사전을 매개변수로 전달합니다. 두 번째 사전은 업데이트된 값에 사용됩니다.

파이썬3




# Python program to show working> # of update() method in Dictionary> # Dictionary with three items> Dictionary1> => {> 'A'> :> 'Geeks'> ,> 'B'> :> 'For'> , }> Dictionary2> => {> 'B'> :> 'Geeks'> }> # Dictionary before Updation> print> (> 'Original Dictionary:'> )> print> (Dictionary1)> # update the value of key 'B'> Dictionary1.update(Dictionary2)> print> (> 'Dictionary after updation:'> )> print> (Dictionary1)>

산출:

Original Dictionary: {'A': 'Geeks', 'B': 'For'} Dictionary after updation: {'A': 'Geeks', 'B': 'Geeks'} 

Iterable로 업데이트

이 예에서는 다른 사전을 사용하는 대신 반복 가능한 값을 update() 함수에 전달했습니다.

파이썬3




# Python program to show working> # of update() method in Dictionary> # Dictionary with single item> Dictionary1> => {> 'A'> :> 'Geeks'> }> # Dictionary before Updation> print> (> 'Original Dictionary:'> )> print> (Dictionary1)> # update the Dictionary with iterable> Dictionary1.update(B> => 'For'> , C> => 'Geeks'> )> print> (> 'Dictionary after updation:'> )> print> (Dictionary1)>

산출

Original Dictionary: {'A': 'Geeks'} Dictionary after updation: {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} 

키가 존재하는 경우 Python 사전 업데이트 값

이 예에서는 특정 키가 존재하는 경우 Python에서 사전 값을 업데이트합니다. 키가 사전에 없으면 키가 존재하지 않는다고 간단히 인쇄합니다.

파이썬3




def> checkKey(> dict> , key):> > > if> key> in> dict> .keys():> > print> (> 'Key exist, '> , end> => ' '> )> > dict> .update({> 'm'> :> 600> })> > print> (> 'value updated ='> ,> 600> )> > else> :> > print> (> 'Not Exist'> )> dict> => {> 'm'> :> 700> ,> 'n'> :> 100> ,> 't'> :> 500> }> > key> => 'm'> checkKey(> dict> , key)> print> (> dict> )>

산출:

Key exist, value updated = 600 {'m': 600, 'n': 100, 't': 500} 

키가 존재하지 않는 경우 Python 사전 업데이트 값

여기서는 사전에 키가 없는 사전의 값을 업데이트해 보겠습니다. 이 경우 키와 값은 사전에 새 요소로 추가됩니다.

파이썬3




def> checkKey(> dict> , key):> > > if> key> not> in> dict> .keys():> > print> (> 'Key doesn't exist So, a new Key-Value pair will be created'> )> > dict> .update({key:> 600> })> > else> :> > print> (> 'Key Exist'> )> dict> => {> 'm'> :> 700> ,> 'n'> :> 100> ,> 't'> :> 500> }> > key> => 'k'> checkKey(> dict> , key)> print> (> dict> )>

산출:

Key doesn't exist So, a new Key-Value pair will be created {'m': 700, 'n': 100, 't': 500, 'k': 600} 


마음에 드실지도 몰라요