Working with Dictionary in Python for Competitive Programming - Beginners

A Dictionary in Python is an ordered collection of key value pair. Learn how to work with Dictionary in Python for Competetive Programming.

Working with Dictionary in Python for Competitive Programming - Beginners
Photo by Florian Berger / Unsplash

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.

d1 = {}
d2 = dict()
Define a Dictionary in Python

To define and initialize a dictionary at once, we can do the following.

d3 = {'Key1':'Value1', 'Key2': 'Value2'}
Initialize a Dictionary in Python

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.

tup = [(1,'hello'), (2, 'World')]
Initialize a Dictionary in Python

The preceding tuple can be provided as an argument to the dict() to create a dictionary as follows.

tup = [(1,'hello'), (2, 'World')]
d4 = dict(tup)
print(d4)
Initialize a Dictionary in Python

The output of the preceding code will be as follows.

{1: 'hello', 2: 'World'}
Output: Initialize a Dictionary in Python

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.

dict[key] = value
Syntax to add a Key Value pair to Dictionary in Python

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.

d1['Website'] = 'WowDataScience'
d1['Url'] = 'https://wowdata.science'
Add Key Value pair to 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.

d1.get('Website')
Access a key value pair of a dictionary using get method in Python

This will print the following output.

'WowDataScience'
Output when a key value pair of a dictionary is accessed using get method in Python

On the contrary, if you try to access a key that doesn't exists, you might want to see a custom message when set.

d1.get('randomkey', 'Key Not Found')
Access a key value pair of a dictionary using get method in Python
'Key Not Found'
Output when a key value pair of a dictionary is accessed using get method in Python

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

dict[key]
syntax to access an element in the dictionary given a key in Python

For example, if you want to access the value of the key 'Website' you can do it as follows.

d1['Website']
Access an element in the dictionary given a key in Python

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.

dict[existingkey] = newvalue
Syntax to update the value of element given its key of a Dictionary in Python

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.

d1['Website'] = 'Wow Data Science'
Update the value of element given its key of a Dictionary in Python

Display all the key value pair in the Dictionary in Python

Let's print all the key value pair of the dictionary in Python.

print(d1)
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.

mydict = dict()
mydict['name'] = 'A Python Dictionary'
mydict[123] = 'I belong to the key 123 of type integer'
mydict[('fruits', 'vegetables')] = 'I belong to the key of type tuple'
mydict[None] = 'I belong to the key of None type'
Add keys of different data types to a Dictionary in Python

Let's print the dictionary mydict that has keys of different data types.

print(mydict)
Print the dictionary mydict that has keys of different data types in Python

This will print the following dictionary as output.

{'name': 'A Python Dictionary', 123: 'I belong to the key 123 of type integer', ('fruits', 'vegetables'): 'I belong to the key of type tuple', None: 'I belong to the key of None type'}
Output when we print the dictionary mydict that has keys of different data types in Python

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.

dict.pop(keytodelete)
Syntax to delete a key value pair from a dictionary using pop method in Python

Let's delete the key 'name' from the dictionary mydict.

mydict.pop('name')
Delete a key value pair from a dictionary using pop method in Python

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'.

{123: 'I belong to the key 123 of type integer', ('fruits', 'vegetables'): 'I belong to the key of type tuple', None: 'I belong to the key of None type'}
Output when we print the dictionary mydict that has keys of different data types in Python
  • 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 to pop method as mydict.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.

del dict[keytodelete]
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.

del mydict[123]
Delete a key value pair from a dictionary using del keyword in Python

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.

{('fruits', 'vegetables'): 'I belong to the key of type tuple', None: 'I belong to the key of None type'}
Output when we print the dictionary mydict that has keys of different data types in Python

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.

mydict.clear()
Delete a key value pair from a dictionary using clear method in Python

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.