Agregue un par clave:valor al diccionario en Python
Diccionario en Python es una colección desordenada de valores de datos, que se utiliza para almacenar valores de datos como un mapa, que a diferencia de otros tipos de datos que contienen solo un valor único como elemento, el Diccionario contiene un par clave:valor. Mientras usamos el Diccionario, a veces necesitamos agregar o modificar la clave/valor dentro del diccionario. Veamos cómo agregar un par clave:valor al diccionario en Python.
Código #1: Uso de la notación de subíndice Este método creará un nuevo par clave:valor en un diccionario asignando un valor a esa clave.
Python3
# 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> )> |
Producción:
El dictado actual es: {'key2': 'for', 'key1': 'geeks'} El dictado actualizado es: {'key3': 'Geeks', 'key5': 'portal', 'key6': 'Computadora', 'clave4': 'es', 'clave1': 'geeks', 'clave2': 'para'}
Complejidad del tiempo: O(1)
Espacio Auxiliar: O(1)
Código #2: Usando el método de actualización()
Python3
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> )> |
Producción:
El dictado actual es: {'key2': 'for', 'key1': 'geeks'} {'newkey1': 'portal', 'key4': 'is', 'key2': 'for', 'key1': 'geeks', 'key5': 'fabuloso', 'key3': 'geeks'}
Complejidad del tiempo: O(1)
Espacio Auxiliar: O(1)
Código #3: Tomando clave: valor como entrada
Python3
# 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)> |
Producción:
{'1': 'Geeks', 2: 'forGeeks'} Complejidad del tiempo: O(1)
Espacio Auxiliar: En)
Código #4: Usando un diccionario de comprensión
Por ejemplo, puede crear un nuevo diccionario que agregue un par clave:valor a un diccionario existente como este:
Python3
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> |
Producción
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} Esto crea un nuevo diccionario llamado dict_actualizado que contiene todos los pares clave:valor de dict_existente, así como el nuevo par clave:valor 'clave3': 'valor3'.
Complejidad del tiempo: En)
Espacio Auxiliar: En)