Open In App

How to create a Dictionary in Python

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Create a Dictionary in Python

In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by a ‘comma’. Let us see a few examples to see how we can create a dictionary in Python.

Define a Dictionary with Items

In this example, we first declared an empty dictionary D, then added the elements from the Python list L into the dictionary. The first element of each of the sublists is the key and the second element is the value. We will store the key-value pair dynamically.

Python3




# 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)


Output:

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

An Overview of Keys and Values

In this example, we will add another element to the existing dictionary in Python. We are provided with the key and value separately and will add this pair to the dictionary my_dict.

Python3




# 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)


Output:

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

Built-in Dictionary Functions Methods in Python

A dictionary in Python can also be created by the built-in function dict(). In this example, we first created an empty dictionary using curly braces {}. Then we used the dict() method and passed a list to it.

Python3




# Creating an empty Dictionary
Dict = {}
my_list = [(1, 'Geeks'), (2, 'For')]
print(my_list)
 
# Creating a Dictionary
# with each item as a Pair
print("\nDictionary with the use of dict(): ")
Dict = dict(my_list)
print(Dict)


Output:

[(1, 'Geeks'), (2, 'For')]

Dictionary with the use of dict(): 
{1: 'Geeks', 2: 'For'}


Previous Article
Next Article

Similar Reads

Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
three90RightbarBannerImg