Dictionaries in Python are a collection of key-value pairs that are unordered and can be changed by use of built-in methods. Dictionaries are used to create a map of unique keys to values that are called items. In this article, we will discuss different operations on dictionaries in Python.
- What are Dictionaries in Python?
- Create a New Dictionary in Python
- Add Values to Dictionaries in Python
- Remove a Key and its Value From a Dictionary
- Check The Length of a Dictionary in Python
- Check if a Key Exists in Python Dictionaries
- Get the Value of a Specified Key in a Dictionary
- Get Only The Keys From The Dictionary
- Print All The Keys in a Dictionary
- Print All The Keys and Values in Python Dictionaries
- Printing The Values in a Dictionary
- Printing Python Dictionaries With pprint Module
- Sorting The Keys of a Dictionary in Python
- Conclusion
What are Dictionaries in Python?
A dictionary in Python is a collection of key-value pairs separated. Here, we need to separate the key and value in a pair with the colon character “:” and different key-value pairs with commas “,” between each pair. A simple dictionary in Python looks as follows.
myDict={1:11,"Name":"PFB", "Code":1117}
In the above dictionary, 1, “Name”, and “Code” are keys of the dictionary whereas 11, “PFB”, and “Code” are the associated values.
The keys in a dictionary must be immutable objects like strings, integers, etc. The values can be of any data type. Also, we cannot have duplicate keys in a Python dictionary.
A dictionary maps a set of objects (keys) to another set of objects (values) so you can create an unordered list of objects. Dictionaries are unordered, so the order that the keys are added doesn’t necessarily reflect what order they may be reported back. Because of this, you can refer to a value by its key name.
Dictionaries are mutable, which means they can be changed. You can add and remove as many key-value pairs to the dictionary as you want. The only condition is that the keys shouldn’t be duplicates.
Create a New Dictionary in Python
In order to construct a dictionary you can start with an empty one. To create an empty dictionary, you can simply assign empty curly braces to a variable as shown below.
myDict={}
print("The dictinary is:")
print(myDict)
Output:
The dictinary is:
{}
You can also use the dict() function to create an empty dictionary. When we execute the dict() function without any input arguments, it returns an empty dictionary as shown below.
myDict=dict()
print("The dictinary is:")
print(myDict)
Output:
The dictinary is:
{}
In the above code, you can observe that the dict() function returns an empty dictionary.
To create Python dictionaries with key-value pairs, you can use the curly braces approach as well as the dict() function.
To create a dictionary with key-value pairs using the curly braces, you can enclose the key-value pairs inside the curly braces. For example, the following code creates a dictionary with six key-value pairs, where iPhone names are keys and their launch years are the associated values.
myDict={"iphone" : 2007,
"iphone 3G" : 2008,"iphone 3GS" : 2009,"iphone 4" : 2010,
"iphone 4S" : 2011,
"iphone 5" : 2012}
print("The dictinary is:")
print(myDict)
Output:
The dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
You can also create a dictionary using the dict() method. For this, you need to convert a list of tuples to a dictionary. The tuples in the given list should contain exactly two items. Each tuple is converted into a key-value pair where the first element in the tuple is converted into key and the second element is converted into the associated value. To understand this, suppose that we have the following list of tuples.
myTuple=[('iphone', 2007), ('iphone 3G', 2008), ('iphone 3GS', 2009), ('iphone 4', 2010), ('iphone 4S', 2011), ('iphone 5', 2012)]
In the above list of tuples, we have six tuples, each containing two elements. We can convert this list of tuples into a Python dictionary as shown below.
myTuple=[('iphone', 2007), ('iphone 3G', 2008), ('iphone 3GS', 2009), ('iphone 4', 2010), ('iphone 4S', 2011), ('iphone 5', 2012)]
print("The tuple is:")
print(myTuple)
myDict=dict(myTuple)
print("The dictinary is:")
print(myDict)
Output:
The tuple is:
[('iphone', 2007), ('iphone 3G', 2008), ('iphone 3GS', 2009), ('iphone 4', 2010), ('iphone 4S', 2011), ('iphone 5', 2012)]
The dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
In the output, you can observe that each tuple in the list of tuples is converted into a key-value pair in the output dictionary.
Add Values to Dictionaries in Python
You can add a value to the dictionary using the Python indexing operator using the following syntax.
myDict[new_key]=new_value
Here, myDict is an existing dictionary whereas new_key must be an immutable value like a string or integer. new_value can take any value. To understand this, consider the following example.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
myDict["iphone 14"]=2022
print("The updated dictinary is:")
print(myDict)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The updated dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012, 'iphone 14': 2022}
In the above example, we have added the key “iphone 14” with the value 2022. In the output dictionary, you can observe that the key-value pair is present in the dictionary.
You can also change the value associated with a key using the above indexing operator as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
myDict["iphone"]=2005
print("The updated dictinary is:")
print(myDict)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The updated dictinary is:
{'iphone': 2005, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
In this example, we assigned the value 2005 to the key “iphone”. As the key “iphone” already exists in the dictionary, the value associated with “iphone” gets updated to 2005.
Remove a Key and its Value From a Dictionary
You can remove an element with the del operator. For this, you just need to retrieve the item of the dictionary using the key name and pass it to the del statement using the following syntax.
del myDict[key_name]
Here, key_name is the key of the key-value pair that we want to delete from the dictionary myDict. You can observe this in the following example.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
del myDict["iphone"]
print("The updated dictinary is:")
print(myDict)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The updated dictinary is:
{'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
In the above example, you can observe that the key “iphone” with its value gets deleted after executing the del statement.
In the above code, if the key that we want to delete doesn’t exist in the dictionary, the program will run into a Python KeyError exception. You can observe this in the following example.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
del myDict["iphone 13"]
print("The updated dictinary is:")
print(myDict)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/tmp/ipykernel_6318/3954324122.py in <module>
2 print("The existing dictinary is:")
3 print(myDict)
----> 4 del myDict["iphone 13"]
5 print("The updated dictinary is:")
6 print(myDict)
KeyError: 'iphone 13'
In the above code, we tried to delete the key “iphone 13”. As this key doesn’t exist in the dictionary, the program runs into a KeyError exception in Python.
You can also delete keys from python dictionaries using the pop() method. The pop() method, when invoked on a dictionary, takes a key as its input argument and removes the key with its value from the dictionary. You can observe this in the following example.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
myDict.pop("iphone")
print("The updated dictinary is:")
print(myDict)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The updated dictinary is:
{'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
Again, if the key passed to the pop() method isn’t present in the dictionary, the program will run into a key error exception.
Check The Length of a Dictionary in Python
You can check the length of a dictionary using the len() function. The len() function takes the dictionary as its input argument and returns the number of key-value pairs in the dictionary. In other words, it tells how many items are present in the dictionary. You can observe this in the following example.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
length=len(myDict)
print("The number of key-value pairs in the dictinary is:")
print(length)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The number of key-value pairs in the dictinary is:
6
In the above example, the len() function returns the value 6 as there are six key-value pairs in the dictionary.
Check if a Key Exists in Python Dictionaries
To check if a key exists in a given dictionary, you can use the in operator. If the key exists in the dictionary, the membership operator will return True. Otherwise, it returns False. You can observe this in the following example.
>>> my_dict = {'a' : 'one', 'b' : 'two'}
>>> 'a' in my_dict
True
>>> 'b' in my_dict
True
>>> 'c' in my_dict
False
You can also use a for loop and iterate over the dictionary to check if a key is present in the given dictionary as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
key_to_check="iphone 4"
print("The key to check is:",key_to_check)
for keys in myDict:
if keys==key_to_check:
print("The key is present in the dictionary.")
break
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The key to check is: iphone 4
The key is present in the dictionary.
Get the Value of a Specified Key in a Dictionary
When we access values from Python dictionaries using the indexing operator, the program might run into an exception if the key isn’t present in the dictionary. We can use the get() method to avoid the error.
The get() method, when invoked on a Python dictionary, takes the key as its first input argument and a default value as its second input argument. If the key exists in the dictionary, the get() method returns the value associated with the key. Otherwise, it returns the default value. You can observe this in the following example.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
key_name="iphone 4"
print("The key is:",key_name)
value=myDict.get(key_name,0)
print("The value associated with the key is:",value)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The key is: iphone 4
The value associated with the key is: 2010
In the above code, the get() method returns 2010 as the key “iphone 4” is present in the dictionary. Here, we passed the default value 0 to the get() method. Hence, if a key isn’t present in the dictionary, the get() method will return 0 as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
key_name="iphone 13"
print("The key is:",key_name)
value=myDict.get(key_name,0)
print("The value associated with the key is:",value)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The key is: iphone 13
The value associated with the key is: 0
In this example, the get() method returns 0 as the key “iphone 13” isn’t present in the dictionary.
Get Only The Keys From The Dictionary
To get all the keys from a dictionary, we can use the keys() method. The keys() method, when invoked on a dictionary, returns a dict_keys object containing all the keys. You can convert the dict_keys object to a list using the list() function as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
keys=myDict.keys()
print("The dict_keys object is:")
print(keys)
list_of_keys=list(keys)
print("The list of keys is:")
print(list_of_keys)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The dict_keys object is:
dict_keys(['iphone', 'iphone 3G', 'iphone 3GS', 'iphone 4', 'iphone 4S', 'iphone 5'])
The list of keys is:
['iphone', 'iphone 3G', 'iphone 3GS', 'iphone 4', 'iphone 4S', 'iphone 5']
Print All The Keys in a Dictionary
You can print all the keys of a dictionary using a for loop as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
print("The keys in the dictionary are:")
for keys in myDict:
print(keys)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The keys in the dictionary are:
iphone
iphone 3G
iphone 3GS
iphone 4
iphone 4S
iphone 5
Instead of directly iterating over the dictionary, you can also get all the keys in the dictionary using the keys() method and print them as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
print("The keys in the dictionary are:")
for keys in myDict.keys():
print(keys)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The keys in the dictionary are:
iphone
iphone 3G
iphone 3GS
iphone 4
iphone 4S
iphone 5
Print All The Keys and Values in Python Dictionaries
To print all the keys and values in a Python dictionary, you can use a for loop and the indexing operator. For this, we will first iterate over the keys in the dictionary using the for loop. Then, we will print the values using the indexing operator as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
print("The keys and values in the dictionary are:")
for key in myDict.keys():
value=myDict[key]
print("{} ==> {}".format(key,value))
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The keys and values in the dictionary are:
iphone ==> 2007
iphone 3G ==> 2008
iphone 3GS ==> 2009
iphone 4 ==> 2010
iphone 4S ==> 2011
iphone 5 ==> 2012
Instead of the above approach, you can also use the items() method to print keys and values in Python dictionaries.
The items() method, when invoked on a dictionary, returns a list of tuples containing key and value pairs as their elements. All the tuples in the list contain two elements where the first element is the key and the second element is the associated value.
You can iterate over the list of tuples and print the keys and values as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
print("The keys and values in the dictionary are:")
for key,value in myDict.items():
print("{} ==> {}".format(key,value))
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The keys and values in the dictionary are:
iphone ==> 2007
iphone 3G ==> 2008
iphone 3GS ==> 2009
iphone 4 ==> 2010
iphone 4S ==> 2011
iphone 5 ==> 2012
Printing The Values in a Dictionary
You can print the values in a dictionary using a for loop and the indexing operator. Here, we will first iterate over the keys in the dictionary. Then, we will get the values in the dictionary using the indexing operator and print them as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
print("The values in the dictionary are:")
for key in myDict:
value=myDict[key]
print(value)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The values in the dictionary are:
2007
2008
2009
2010
2011
2012
Instead of using the above approach, you can also use the values() method to print values in the Python dictionary. The values() method, when invoked on a dictionary, return a dict_values object containing all the values in the dictionary. You can print all the values by iterating over the dict_values object as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The existing dictinary is:")
print(myDict)
print("The values in the dictionary are:")
for value in myDict.values():
print(value)
Output:
The existing dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The values in the dictionary are:
2007
2008
2009
2010
2011
2012
Printing Python Dictionaries With pprint Module
The print() method prints all the key-value pairs in a single line without any formatting. To format the dictionary while printing, you can use the pprint() function defined in the pprint module. The pprint() function prints the dictionary in a formatted manner as shown below.
import pprint
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The dictinary is:")
print(myDict)
print("The prettry printed dictinary is:")
pprint.pprint(myDict)
Output:
The dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The prettry printed dictinary is:
{'iphone': 2007,
'iphone 3G': 2008,
'iphone 3GS': 2009,
'iphone 4': 2010,
'iphone 4S': 2011,
'iphone 5': 2012}
Sorting The Keys of a Dictionary in Python
You can sort the keys in a given dictionary. for this, you can use the sorted() function. The sorted function takes the dictionary as its input argument and returns a list of keys in sorted sequence as shown below.
myDict={'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
print("The dictinary is:")
print(myDict)
print("The sorted keys are:")
print(sorted(myDict))
Output:
The dictinary is:
{'iphone': 2007, 'iphone 3G': 2008, 'iphone 3GS': 2009, 'iphone 4': 2010, 'iphone 4S': 2011, 'iphone 5': 2012}
The sorted keys are:
['iphone', 'iphone 3G', 'iphone 3GS', 'iphone 4', 'iphone 4S', 'iphone 5']
You can also iterate through the sorted list and use the indexing operator to get the values associated with the keys in a sorted manner.
Conclusion
In this article, we discussed different operations on Python dictionaries. To learn more about Python programming, you can read this article on list comprehension in Python. You might also like this article on dictionary comprehension in Python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
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.