Using set on Dictionary keys in Python

In this tutorial, we will learn how to use a set on the keys of a dictionary with the code snippet.

Dictionary is a unique collection in Python. It contains key-value pairs.  Dictionary can also contain tuple, sets and lists. We can access values in the dictionaries by their keys.  Dictionary has varied uses, as it can hold any type of data in it.


{'Name': 'Adam', 'Age': 27, 'roll': 22}

From this example, you can observe that data types of keys and their values are independent. You can have a string type of key and an integer type of value and visa Versa. To know more about dictionaries in Python please Click here.

Use Set on Python Dictionary Keys

We know that we can access the values of dictionaries using their keys. It is recommended that the keys in the dictionary should be unique while there is no restriction on the values. Python won’t show any error if you repeat the keys but, when you try to access the value using that key, it will only show you the latest value.
Let’s understand this with an example:

dic={'Name':'Vivek Shadi','Roll':65,'Name':'Adam Johnas','Roll':67}
{'Name': 'Adam Johnas', 'Roll': 67}

Set: Set can be defined as a  collection of elements where all elements are unique. To know more about sets, please click here.
We can use set operation on the keys of a dictionary such as, union(|), intersection(&), difference(-), symmetric difference(^).

Now in a dictionary, when we have the same keys we can use set to identify the unique keys.
Set can be very useful when we are working with two dictionaries. Let’s understand this with an example.

d1 = {'a':1,'b':2,'c':3,'f':8}
d2 = {'c':4,'d':5,'e':6,'f':7}

print("1.",d1.keys() | d2.keys())
print("2.",d1.keys() & d2.keys())
print("3.",d1.keys() - d2.keys())
print("4",d1.keys() ^ d2.keys())
1. {'c', 'e', 'f', 'b', 'd', 'a'}
2. {'f', 'c'}
3. {'b', 'a'}
4 {'e', 'b', 'd', 'a'}

the point to note is that whatever the output we are getting here is a set, as mentioned earlier keys should not repeat in a dictionary.

So, internally when we operate on keys to get some desired results the output is in the form of sets. You can also observe all the values in the output are distinct and unique.

Let’s say we have two dictionaries Employee and Student, and we want to find common keys in both the dictionaries,

Employee={'Name':'Vivek Shadi','EID':789,'Salary':50000,'Wing':'A'}
Student={'Name':'Shreyas Gandhi','RollNo':78,'Fees':2000,'Wing':'D'}

#commmon keys

The out that will be generated from the code will be a set.

{'Name', 'Wing'}
<class 'set'>

So we have learned from the example the use of set on Dictionary keys with Python.

Leave a Reply