0
Q:

add new key in dictionary python

d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
21
# Basic syntax:
dictionary['new_key'] = value

# Example:
d = {'a': 1, 'b': 5} # Define dictionary
d['c'] = 37 # Add a new key to the dictionary
print(d)
--> {'a': 1, 'b': 5, 'c': 37}
1
d = {'key': 'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'key': 'value', 'mynewkey': 'mynewvalue'}
0
dict = {'key1':'geeks', 'key2':'for'} 
print("Current Dict is: ", dict) 
  
# adding key3 
dict.update({'key3':'geeks'}) 
print("Updated Dict is: ", dict) 
  
# adding dict1 (key4 and key5) to dict 
dict1 = {'key4':'is', 'key5':'fabulous'} 
dict.update(dict1) 
print(dict) 
  
# by assigning  
dict.update(newkey1 ='portal') 
print(dict) 
4
dict = {'key1':'addme', 'key2':'fill_me'} 
print("Current Dict is: ", dict) 
  
# using the subscript notation 
# Dictionary_Name[New_Key_Name] = New_Key_Value 
dict['key2'] = 'for'
dict['key3'] = 'newtask'
print("Updated Dict is: ", dict) 
-1
# Let's create 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() 
  
dict_obj.add(1, 'Geeks') 
dict_obj.add(2, 'forGeeks') 
  
print(dict_obj) 
-2

New to Communities?

Join the community