Sai A Sai A
Updated date Mar 13, 2024
In this blog, we will learn how to convert a dictionary to a set in Python, exploring multiple methods with practical examples and explanations.

Method 1: Using Dictionary Keys

To convert a dictionary into a set is by extracting its keys. Since keys in a dictionary are unique, they can be directly used to create a set.

# Create a dictionary
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

# Convert dictionary keys to a set
my_set = set(my_dict.keys())

# Print the set
print(my_set)

Output:

{'apple', 'banana', 'orange'}

In this method, we use the keys() method of the dictionary to obtain a list of keys. We then pass this list to the set() function to create a set containing all the keys. Since sets only store unique elements, any duplicate keys are automatically removed.

Method 2: Using Dictionary Values

Similar to using keys, we can also convert a dictionary into a set by extracting its values.

# Create a dictionary
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

# Convert dictionary values to a set
my_set = set(my_dict.values())

# Print the set
print(my_set)

Output:

{1, 2, 3}

In this method, we use the values() method of the dictionary to obtain a list of values. We then pass this list to the set() function to create a set containing all the unique values from the dictionary.

Method 3: Using Dictionary Items

Alternatively, we can directly convert dictionary items into a set. Each item in a dictionary is a key-value pair, and since sets only store unique elements, this method effectively removes any duplicate keys or values.

# Create a dictionary
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

# Convert dictionary items to a set
my_set = set(my_dict.items())

# Print the set
print(my_set)

Output:

{('banana', 2), ('apple', 1), ('orange', 3)}

In this method, we use the items() method of the dictionary to obtain a list of key-value pairs. We then pass this list to the set() function to create a set containing all the unique items from the dictionary.

Comments (0)

There are no comments. Be the first to comment!!!