Python의 사전에 키:값 쌍 추가

사전 Python에서 맵과 같은 데이터 값을 저장하는 데 사용되는 정렬되지 않은 데이터 값 모음입니다. 단일 값만 요소로 보유하는 다른 데이터 유형과 달리 Dictionary는 키:값 쌍을 보유합니다. Dictionary를 사용하다 보면 가끔 Dictionary 내부의 키/값을 추가하거나 수정해야 하는 경우가 있습니다. Python에서 사전에 키:값 쌍을 추가하는 방법을 살펴보겠습니다.

코드 #1: 아래 첨자 표기법 사용 이 방법은 해당 키에 값을 할당하여 사전에 새 키:값 쌍을 생성합니다.

파이썬3






# Python program to add a key:value pair to dictionary> dict> => {> 'key1'> :> 'geeks'> ,> 'key2'> :> 'for'> }> print> ('Current> Dict> is> : ',> dict> )> > # using the subscript notation> # Dictionary_Name[New_Key_Name] = New_Key_Value> dict> [> 'key3'> ]> => 'Geeks'> dict> [> 'key4'> ]> => 'is'> dict> [> 'key5'> ]> => 'portal'> dict> [> 'key6'> ]> => 'Computer'> print> ('Updated> Dict> is> : ',> dict> )>

산출:

현재 사전: {'key2': 'for', 'key1': 'geeks'} 업데이트된 사전: {'key3': 'Geeks', 'key5': 'portal', 'key6': 'Computer', 'key4': 'is', 'key1': '괴짜', 'key2': 'for'}

시간 복잡도: 오(1)
보조 공간: 오(1)

코드 #2: update() 메소드 사용

파이썬3




dict> => {> 'key1'> :> 'geeks'> ,> 'key2'> :> 'for'> }> print> ('Current> Dict> is> : ',> dict> )> # adding dict1 (key3, key4 and key5) to dict> dict1> => {> 'key3'> :> 'geeks'> ,> 'key4'> :> 'is'> ,> 'key5'> :> 'fabulous'> }> dict> .update(dict1)> # by assigning> dict> .update(newkey1> => 'portal'> )> print> (> dict> )>

산출:

현재 사전은 다음과 같습니다: {'key2': 'for', 'key1': 'geeks'} {'newkey1': 'portal', 'key4': 'is', 'key2': 'for', 'key1': '괴짜', 'key5': '멋진', 'key3': '괴짜'}

시간 복잡도: 오(1)
보조 공간: 오(1)

코드 #3: 키:값을 입력으로 사용

파이썬3




# Let's add key:value to a dictionary, the functional way> # Create your dictionary class> class> my_dictionary(> dict> ):> > # __init__ function> > def> __init__(> self> ):> > self> => dict> ()> > > # Function to add key:value> > def> add(> self> , key, value):> > self> [key]> => value> # Main Function> dict_obj> => my_dictionary()> # Taking input key = 1, value = Geek> dict_obj.key> => input> ('Enter the key: ')> dict_obj.value> => input> ('Enter the value: ')> dict_obj.add(dict_obj.key, dict_obj.value)> dict_obj.add(> 2> ,> 'forGeeks'> )> print> (dict_obj)>

산출:

 {'1': 'Geeks', 2: 'forGeeks'} 

시간 복잡도: 오(1)
보조 공간: 에)

코드 #4: 사전 이해를 사용하여

예를 들어 다음과 같이 기존 사전에 키:값 쌍을 추가하는 새 사전을 생성할 수 있습니다.

파이썬3




existing_dict> => {> 'key1'> :> 'value1'> ,> 'key2'> :> 'value2'> }> new_key> => 'key3'> new_value> => 'value3'> updated_dict> => {> *> *> existing_dict, new_key: new_value}> print> (updated_dict)> #This code is contributed by Edula Vinay Kumar Reddy>

산출

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} 

이는 기존_dict의 모든 키:값 쌍과 새 키:값 쌍 'key3': 'value3'을 포함하는 update_dict라는 새 사전을 생성합니다.

시간 복잡도: 에)
보조 공간: 에)



인기 기사

범주

재미있는 기사