Skip to main content

How to convert a dictionary to a dictionary of sets in Python

How to convert a dictionary to a dictionary of sets in Python.

Here's a step-by-step tutorial on how to convert a dictionary to a dictionary of sets in Python:

Step 1: Create a Dictionary

Start by creating a dictionary in Python. A dictionary consists of key-value pairs, where each key is unique. For example, let's create a dictionary called my_dict:

my_dict = {'A': 1, 'B': 2, 'C': 3}

Step 2: Initialize an Empty Dictionary of Sets

Next, initialize an empty dictionary that will hold sets as its values. Let's call it set_dict:

set_dict = {}

Step 3: Iterate through the Original Dictionary

Using a loop, iterate through each key-value pair in the original dictionary. For each key-value pair, we will convert the value to a set and add it to the new dictionary.

for key, value in my_dict.items():
set_dict[key] = {value}

In this example, we are creating a new set for each value and assigning it as the value in the set_dict dictionary. The key remains the same.

Step 4: Update Existing Sets

If you have an existing dictionary of sets and you want to add or update values, you can modify the code from step 3. Instead of creating a new set for each value, you can update the existing set for the corresponding key.

for key, value in my_dict.items():
if key in set_dict:
set_dict[key].add(value)
else:
set_dict[key] = {value}

This code checks if the key already exists in the set_dict dictionary. If it does, it adds the value to the existing set using the add() method. If the key doesn't exist, it creates a new set with the value.

Step 5: Print the Resulting Dictionary of Sets

To verify the conversion, you can print the resulting dictionary of sets. Here's an example of how to print the set_dict:

print(set_dict)

This will output the dictionary of sets:

{'A': {1}, 'B': {2}, 'C': {3}}

That's it! You have successfully converted a dictionary to a dictionary of sets in Python.