In python, a dictionary is a data structure in which we can keep data in the form of key-value pairs.In this article, we will study and implement various methods to create a dictionary in python.
Create an empty dictionary in python
We can create an empty python dictionary using curly braces or a dictionary constructor.
To create an empty dictionary using curly braces, we simply declare a variable and assign a pair of curly braces as shown below.
myDict={}
print("Created dictionary is:")
print(myDict)
Output:
Created dictionary is:
{}
In the output above, the curly braces show that an empty dictionary has been created.
To create an empty dictionary using a dictionary constructor, we can simply call the constructor dict()
and assign it to a variable as follows.
myDict=dict()
print("Created dictionary is:")
print(myDict)
Output:
Created dictionary is:
{}
In the above program, we have used dict()
constructor to create an empty dictionary. We can also use the above methods to create dictionaries with key value pairs already defined which has been discussed in following sections.
Create dictionary with key value pairs already defined
To create a dictionary using already defined key value pairs, we can either use the curly braces, dictionary constructor or dictionary comprehension.
To create a dictionary with predefined key value pairs using curly braces, we simply write the key value pairs using colon and separate each key value pair using comma as shown below.
myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Created dictionary is:")
print(myDict)
Output:
Created dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
In the above program, we have created a dictionary having name
and acronym
as keys and PythonForBeginners
and PFB
as respective values for the keys in the dictionary. We can perform the same operation using dictionary constructor.
While creating a dictionary with predefined key value pairs using a dictionary constructor, we pass the keys and values as keyword parameters to the python dictionary constructor as shown below.
myDict=dict(name="PythonForBeginners",acronym="PFB")
print("Created dictionary is:")
print(myDict)
Output:
Created dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
In the output, we can see that we have created a dictionary same as previous method but have used dict()
constructor for the same purpose. In the program, the key value pairs have been passed as keyword parameters to the constructor where keys of the dictionary as passed as keyword for the parameters and respective values for the keys of the dictionary have been passed as values to the keyword parameters.
We can also create dictionaries when we are given tuples containing key and value pairs. In this case value at index 0 of the tuple becomes the key for the dictionary and value at index 1 of the tuple becomes value for the respective key in the dictionary.
When we have key-value pairs in a list having tuples containing key and value in each tuple, we can create a dictionary using the dictionary constructor as follows.
myList=[("name","PythonForBeginners"),("acronym","PFB")]
myDict=dict(myList)
print("Created dictionary is:")
print(myDict)
Output:
Created dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
In the above program, we can verify that keys of the dictionary are created from elements at index 0 in the tuples and values for respective keys are generated from elements at index 1 of the tuples.
It may be possible that we are given a list of keys and a separate list of values to be included in the dictionary. To create the dictionary, we first need to make tuples of key value pairs and then we can create a dictionary using those key value pairs.To create tuples containing key and value pairs, we can use the zip()
function.
The zip()
function takes two iterables and does one on one mapping from elements of first iterable to elements of second iterable (based on indexes). If there are extra elements in any of the iterable, they are left out.
We can create a python dictionary using given lists of keys and values by using the zip()
function and dictionary constructor as follows.
keyList=["name","acronym"]
valueList=["Pythonforbeginners","PFB"]
temp=zip(keyList,valueList)
print("given list of keys is:")
print(keyList)
print("given list of values is:")
print(valueList)
print("Created key value pairs are:")
myList=list(temp)
print(myList)
myDict=dict(myList)
print("Created dictionary is:")
print(myDict)
Output:
given list of keys is:
['name', 'acronym']
given list of values is:
['Pythonforbeginners', 'PFB']
Created key value pairs are:
[('name', 'Pythonforbeginners'), ('acronym', 'PFB')]
Created dictionary is:
{'name': 'Pythonforbeginners', 'acronym': 'PFB'}
In the above program, first a list containing tuples of key value pairs is generated using zip()
function and then we create a dictionary from the list of tuples using dictionary constructor.
Create dictionary using dictionary comprehension
Just as we use list comprehension for creating lists in python, we can use dictionary comprehension to create dictionaries in python.We can create a dictionary from another dictionary or other iterable by creating key value pairs for the new dictionary from the given iterable or dictionary.
Suppose we want to create a dictionary containing elements from a list as keys and their squares as values, we can do it as follows.
myList=[1,2,3,4]
myDict={x:x**2 for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)
Output:
List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
In the output, we can see that the created dictionary contains the elements of the list as keys and squares of the elements as respective values for the keys of the dictionary.
We can also create a new dictionary by selecting key value pairs from another dictionary based on a certain condition. For this task we can get the list of key value pairs as tuples using items()
method and then we can use the tuples having key value pairs to create a new dictionary according to any given condition.
Suppose we want to create a new dictionary in which only those key value pairs of the original dictionary are selected which have an even number as key. This can be done as follows.
myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items() if key%2==0}
print("New dictionary is:")
print(newDict)
Output:
Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{2: 4, 4: 16}
In the above output, we can see that we have selectively chosen the key value pairs for the new dictionary from the original dictionary and the new dictionary only contains the keys which are even numbers. We have also modified the respective values by squaring them.
Conclusion
In this article, we have seen several ways to create dictionaries in python. We have seen how to create dictionaries using curly braces, dictionary constructor and dictionary comprehension by implementing different programs in python. Stay tuned for more informative articles.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.