What is a dictionary in Python? What are the commands to perform various operations on the Dictionary?
The operation includes creating the dictionary, adding a new element, updating elements, deleting the dictionary.
Here is a complete Python dictionary tutorial for you.
At the end of this tutorial, you will also find some of the important methods you can use with the dictionary. These simple methods will make your programming go easy.
Let’s start…
Table of Contents
It is a data structure in Python that stores the data in key-value pairs.
For example:
empAge = {'Mark': 23, 'Bob': 45}
The empAge
is a dictionary object which stores an employee’s name and age in the key-value format.
Properties / Characteristics of dictionary:
These are the simple things you should always remember while using a Python dictionary.
Following is the simple syntax for creating a Python dictionary.
How to create an empty dictionary?
myDict = {}
Here, myDict
is the new dictionary object. You can give any name to the dictionary object.
How to create a dictionary with integer keys?
empDict = {1: 'Mark', 2: 'Bob'}
Here is the empDict
object which stores the employee’s ID as a key and his name as value.
Employee ID is an integer (one of the numeric data types in Python).
How to create a dictionary with mixed key data types?
Instead of just using an integer value as a key we can also mix the data types of key.
empDict = {1: 'Mark', 'salary': 200}
In the above example, the first pair of key-value has an integer key (1). The second key-value pair has a string key (‘salary’).
How to create a dictionary using dict()?
empDict = dict({1: 'Mark', 2: 'Bob'})
Here, dict
is just an extra keyword. You can use it or skip it, based on how you feel comfortable with.
However, as per the flake8 standard for writing the Python dictionary, it is recommended to use the dictionary literal ({}
) instead of dict()
method.
These are all different methods for creating a dictionary in Python. You can choose which suits best your requirement and feel comfortable with them.
Every key in the dictionary is mapped to the value. So, while retrieving any value from the dictionary you have to provide key elements. And you will get a value corresponding to the key in return.
There are two ways of doing it.
Using key as indexing
print(myDict['name']) #indexing
Using get method
print(myDict.get('age')) #method
Sometimes, the key you provide in the get() method may not be present. In this case, you can set the default value for the key that is not present.
Let say we already have a dictionary with some elements in it.
empDict = {1: 'Mark', 2: 'Bob'}
Updating existing discretionary value:
If the key is already present in the dictionary, it will overwrite the value, to preserve the uniqueness of the key.
empDict = {1: 'Mark', 2: 'Bob'} empDict[2] = 'Alice' print(empDict) # Output: {1: 'Mark', 2: 'Alice'}
Adding a new element to the dictionary:
If the key is not present in the dictionary, it adds a new key-value pair in the dictionary.
empDict = {1: 'Mark', 2: 'Bob'} empDict[3] ='Alice' print(empDict) # Output: {1: 'Mark', 2: 'Bob', 3:'Alice'}
Note: The syntax for adding and updating elements in the dictionary is the same.
Adding a new element to the dictionary with the same key:
What if we try to add a new element in the dictionary with the key which is already present in the dictionary?
If you try to add the same element in the dictionary with the same keys, it overwrites the key value.
It is similar to updating the value of the given key in the dictionary.
Let’s consider this dictionary.
# create a dictionary squaresDict = {1:1, 2:4, 3:9, 4:16, 5:25}
How to remove a particular element from the dictionary using pop?
You have to specify the key.
Here is a way of doing this using the simple pop method.
print(squaresDict .pop(4)) # Output: 16
The pop method returns the value of the dictionary element you are removing.
When you print the dictionary after performing the pop operation, you don’t see that element in the dictionary.
print(squaresDict ) # Output: {1: 1, 2: 4, 3: 9, 5: 25}
How to remove an arbitrary item for which you know key-value pair using pop?
Use popitem
method for this. You need to provide both key and value here.
print(squaresDict .popitem()) # Output: (1, 1) print(squaresDict) # Output: {2: 4, 3: 9, 5: 25}
How to remove an element from a dictionary using del?
Just like the pop method you can also use the del
object.
# delete a particular item del squaresDict [5] print(squaresDict ) # Output: {2: 4, 3: 9}
The keyword del is not only specific to the dictionary. It is a generic way of deleting any Python object.
Now we are not interested in deleting a single element. What if you want to delete the complete dictionary? Or want to clear all the elements in the dictionary?
Dictionary has a special method called clear to delete all the items from the dictionary.
squaresDict = {1:1, 2:4, 3:9, 4:16, 5:25} squaresDict .clear() # remove all items print(squaresDict ) # Output: {}
You can see the empty dictionary as an output.
How to Delete Complete Dictionary?
Earlier we have tried del object for deleting a particular item from the dictionary. Now you want to delete the complete dictionary object instead of just removing all elements from the dictionary.
Using a del
object, you can delete the complete dictionary.
squaresDict = {1:1, 2:4, 3:9, 4:16, 5:25} del squaresDict # delete the dictionary itself
After deleting the dictionary object, when you try to print the dictionary, it throws an error.
Difference between del and clear method:
If you delete the dictionary using del, it wipes out the complete dictionary object.
If you try to access the dictionary, it will through an error.
empDict = {1: 'Mark', 2: 'Bob'} del empDict print(empDict)
Traceback (most recent call last): File "/home/7d2f6393bbb812bde2a7f038b346bb7e.py", line 5, in print(empDict ) NameError: name 'empDict' is not defined
It means the dictionary has been deleted.
Method clear()
does not delete the dictionary. It removes all the items from the dictionary. Dictionary will be empty.
What is the membership test?
Check if the key is present in the dictionary or not.
squaresDict = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
You can do the membership test using ‘in’.
Syntax:
<expected_key> in <dictionary_object>
It returns true if the key is present in the dictionary.
It returns false if the key is not present in the dictionary.
Example:
print(1 in squaresDict) # Output: True print(4 in squaresDict) # Output: False
“not in”
You can also apply negation ‘not in’.
Slightly different. If the key is not present in the dictionary, it returns True.
Example:
print(2 not in squaresDict) # Output: True
Many times you have to iterate over all the elements in the dictionary.
It is simple.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for i in squares: print(squares[i])
The above example will print all the dictionary elements one-by-one.
Inside for loop, you can write a code to perform any operations on each element of the dictionary.
You can also use the items method for iteration.
Using items methods for iterating over the dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} for item in squares.items(): print(item)
How to create a dictionary from the sequence?
You can use each sequence as a key-value pair. Here is a simple code that works for you.
empDict = dict([(1,'Mark'), (2,'Bob')])
We are using the same dict()
method that was used earlier for creating a dictionary object.
Look at some of the methods you can use with the dictionary.
Let’s take some examples of dictionary methods.
Write a Python code to initialize the dictionary with zero value for all specified keys.
marks = {}.fromkeys(['Math','English','Science'], 0) print(marks) # Output: {'English': 0, 'Math': 0, 'Science': 0}
Using items methods for iterating over the dictionary.
for item in marks.items(): print(item)
Using the keys method to get all the keys present in the dictionary.
list(sorted(marks.keys())) # Output: ['English', 'Math', 'Science']
You can use the comprehension technique to generate the dictionary items.
Write a python code to store the square as the value for each key.
squares = {x: x*x for x in range(6)} print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This is simply equivalent to the following code.
squares = {} for x in range(6): squares[x] = x*x
We can add some more conditions to the comprehension technique.
odd_squares = {x: x*x for x in range(11) if x%2 == 1} print(odd_squares) # Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
There are also some built-in functions you can use with a dictionary.
Let’s check some examples.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
How to find the length of the dictionary (number of items in the dictionary.)
print(len(squares)) # Output: 5
How to sort the items in the dictionary by key?
print(sorted(squares)) # Output: [1, 3, 5, 7, 9]
Other Python Dictionary Tutorials:
This is all about the complete Python dictionary tutorial. If you have any specific questions to discuss, write our query in the comment.
Happy Pythoning!
Well done! That’s the clearest and most comprehensive intro to dictionaries I’ve seen!
I’ll be looking out for your other tutorials!
Thank you so much, Jane, for your kind words! Glad you like it and find it useful.
You gave some examples and then makes a list of dictionary methods. “get” method is great. It also deserves for example. And the comprehension part showed me something that I didn’t see until now. Thanks.
You’re welcome, Marek! And I’m very much glad you like it. I hope you enjoy other tutorials as well. Stay connected 🙂
Thank you very good
You’re welcome!
Wow! That is all I can say. Your examples and explanations are so concise. I really enjoyed how you show different methods for solving the same problem. You did a lot of work organizing this and I will share with everyone I know. Thank You!
Thanks, David for your kind words! This encourages me to write more and share it with you all. I would love it if you give me your two minutes and share your feedback/testimonial https://www.csestack.org/feedback/ . Love!