Convert a Dictionary to a Set in Python

Converting a dictionary to a set allows you to extract unique keys or values from the dictionary. In this blog post, we will explore different methods to convert a dictionary to a set in Python.

Method 1: Using the keys() or values() method

# Method 1: Using the keys() or values() method
my_dict = {"a": 1, "b": 2, "c": 3, "d": 2}
key_set = set(my_dict.keys())
value_set = set(my_dict.values())

print("Keys as Set:", key_set)
print("Values as Set:", value_set)

Output:

Keys as Set: {‘c’, ‘a’, ‘d’, ‘b’}
Values as Set: {1, 2, 3}

Method 2: Using the items() method

# Method 2: Using the items() method
my_dict = {"a": 1, "b": 2, "c": 3, "d": 2}
entry_set = set(my_dict.items())

print("Entries as Set:", entry_set)

Output:

Entries as Set: {(‘c’, 3), (‘b’, 2), (‘a’, 1), (‘d’, 2)}