How to create a Dictionary in Python

Dictionaries are the fundamental data structure in Python and are very important for Python programmers. They are an unordered collection of data values, used to store data values like a map. Dictionaries are mutable, which means they can be changed. They offer a time complexity of O(1) and have been heavily optimized for memory overhead and lookup speed efficiency.

Example 1: The first element of each of the sublists is the key and the second element is the value. We want to store the key-value pair dynamically.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# dynamic dictionary creation
  
  
# Initialize an empty dictionary
D = {} 
  
L = [['a', 1], ['b', 2], ['a', 3], ['c', 4]]
  
# Loop to add key-value pair
# to dictionary
for i in range(len(L)):
    # If the key is already 
    # present in dictionary
    # then append the value 
    # to the list of values
    if L[i][0] in D:
        D[L[i][0]].append(L[i][1])
      
    # If the key is not present
    # in the dictionary then add
    # the key-value pair
    else:
        D[L[i][0]]= []
        D[L[i][0]].append(L[i][1])
          
print(D) 

chevron_right


Output:



{'a': [1, 3], 'b': [2], 'c': [4]}

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to demonstrate
# dynamic dictionary creation
  
  
# Key to be added
key_ref = 'More Nested Things'
my_dict = {
    'Nested Things': [{'name', 'thing one'}, {'name', 'thing two'}]
}
  
# Value to be added
my_list_of_things = [{'name', 'thing three'}, {'name', 'thing four'}]
  
# try-except to take care of errors
# while adding key-value pair
try:
    my_dict[key_ref].append(my_list_of_things)
      
except KeyError:
    my_dict = {**my_dict, **{key_ref: my_list_of_things}}
      
print(my_dict)

chevron_right


Output:

{
 'Nested Things': [{'name', 'thing one'}, {'thing two', 'name'}], 
 'More Nested Things': [{'name', 'thing three'}, {'thing four', 'name'}]
}



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.