Working with Dictionary in Python for Competitive Programming - Beginners
In this tutorial we will see how to work with Dictionary in Python. Dictionary is most widely used composite data type used in Competitive Programming. This step-by-step guide will help you learn about how to work with Dictionaries in Python.
A Dictionary in Python is an ordered collection of key value pair. The type of a Dictionary in Python is identified by the dict
keyword.
Properties of a Dictionary in Python
- Python Dictionary is an ordered collection of key-value pair.
- Python Dictionaries are implemented with the Hash Tables as the underlying data structure.
- Each element in a dictionary is called a Key-Value pair.
- All Keys of a dictionary must be unique.
- A key of a dictionary must be hashable. Un-hashable types such as lists cannot be a key of a dictionary.
- Keys of a dictionary does not have to be of same type. Keys of a
dict
can be of any datatype. - One of the Key of a dictionary can be
None
.
Define a Dictionary in Python
To define or declare a Dictionary in Python, we use {} or dict() and assign it to a variable.
To define and initialize a dictionary at once, we can do the following.
The preceding example shows the in place definition and initialization of the dictionary in Python.
Initializing a dict using list of tuples
The dict()
takes an optional parameter of type list of tuples.
Let's say we have list of tuples as follows.
The preceding tuple can be provided as an argument to the dict()
to create a dictionary as follows.
The output of the preceding code will be as follows.
Type of Dictionary in Python
To check the type of dictionary in Python, we use type(d1)
. The result will be <class 'dict'>
Add a Key Value pair to Dictionary in Python
Following is the syntax to inset or add elements to a dictionary.
In the preceding syntax, the key
can be of any hashable type and value
can be any scalar, composite or custom data type.
For example, the following code snippet shows adding keys and values to a dictionary in Python.
Access a Key Value pair from a Dictionary in Python
Access a key value pair of a dictionary using get method
The safest approach of accessing a key value pair of a dictionary in Python is by using get
method.
The get
method takes two arguments among which the first one is a required argument indicating the key that you want to find the value for in a dictionary. The second one is an optional argument, which indicates the default value to be returned in case the key you are trying to get value for is not found.
This will print the following output.
On the contrary, if you try to access a key that doesn't exists, you might want to see a custom message when set.
The default value of None
will be returned if you do not pass the second argument. Hence, accessing the key value pair of a dictionary using get
is the safest approach.
Access a key value pair by using index syntax
Elements of a dictionary can be accessed given that you know the key that exists in the dictionary.
The syntax to access an element in the dictionary is
For example, if you want to access the value of the key 'Website' you can do it as follows.
The preceding code will return the value 'WowDataScience'
.
When you try to access a value that is not present in the dictionary, it will raise KeyError
. For example, if we call d1['website']
, the program will raise exception KeyError: 'website'
.
This also indicates that strings as keys of a dictionary are case sensitive.
Update a Key Value pair of a Dictionary in Python
Following is the syntax to update the value of element given its key.
Let's update the value for the key 'Website'
in the d1
dictionary from 'WowDataScience'
to string with spaces 'Wow Data Science'
.
The code to update the value given a key of a dictionary is as follows.
Display all the key value pair in the Dictionary in Python
Let's print all the key value pair of the dictionary in Python.
The preceding command will return the following output.
{'Website': 'Wow Data Science', 'Url': 'https://wowdata.science'}
Adding keys of different types to a Dictionary in Python
As a Dictionary in Python is implemented as Hash Table as a reference, the keys can be of any data type.
So, we will add keys of different data types to a Dictionary in Python as follows.
Let's print the dictionary mydict
that has keys of different data types.
This will print the following dictionary as output.
Delete a key value pair from a Dictionary in Python
There are different ways to delete a key value pair from a dictionary. Following are the ways to delete key value pair from a dictionary.
- Using
pop
method available on the dictionary to delete key value from a Dictionary - Using
del
to delete key value from a Dictionary
Using pop method
The following is the syntax to delete a key value pair from a dictionary in Python using pop method.
Let's delete the key 'name'
from the dictionary mydict
.
Now, if we print the mydict
using the command print(mydict)
, we will not see the key value pair that belongs to the key 'name'
.
- The
pop
method will return the value of the key value pair that is deleted. - In case the key you are trying to pop is not found, it will raise
KeyError
. - To prevent raising
KeyError
, you can expect default return value by providing second argument topop
method asmydict.pop('keydoesnotexists', None)
Using del keyword
The following is the syntax to delete a key value pair from a dictionary using del
keyword in Python.
Let's delete the key 123
from the dictionary mydict
.
Now, if we print the mydict
using the command print(mydict)
, we will not see the key value pair that belongs to the key 123
.
Delete all items from a Dictionary in Python
To delete all the items from a dictionary in Python, you can use the clear
method. Let's move ahead and delete all the key value pair in our mydict
dictionary by calling clear
method.
Summary
In this tutorial we learnt various properties of a Dictionary in Python. In addition to that, we also have learnt the following aspects with regards to Dictionary in Python.
- Learnt various ways to define a Dictionary in Python.
- Learnt how to add a Key Value pair to Dictionary in Python.
- Learnt how to access a Key Value pair from a Dictionary in Python.
- Learnt how to update a Key Value pair of a Dictionary in Python.
- Learnt how to display all the key value pair in the Dictionary in Python.
- Learnt how to adding keys of different types to a Dictionary in Python.
- Learnt how to delete a key value pair from a Dictionary in Python.
If you found this tutorial helpful, please do share it with your colleagues and friends.