Skip to main content

Splitting a Python Dictionary into Multiple Dictionaries based on Values

Splitting a Python Dictionary into Multiple Dictionaries based on Values.

In Python, you can split a dictionary into multiple dictionaries based on the values it contains. This can be useful when you want to group the data in the dictionary based on certain criteria. Here is a step-by-step tutorial on how to achieve this.

Step 1: Create a Dictionary

First, let's create a sample dictionary that we will use throughout this tutorial. The dictionary will contain key-value pairs, where the values will be used for splitting.

my_dict = {
'apple': 10,
'banana': 12,
'orange': 9,
'grape': 10,
'kiwi': 12,
'pineapple': 9
}

Step 2: Initialize an Empty Dictionary for Each Value

Next, we need to initialize an empty dictionary for each unique value in the original dictionary. We will use the set() function to get the unique values from the dictionary.

unique_values = set(my_dict.values())
split_dicts = {value: {} for value in unique_values}

In this example, the split_dicts dictionary will have keys as the unique values from my_dict and empty dictionaries as their corresponding values.

Step 3: Iterate over the Original Dictionary

Now, we need to iterate over the original dictionary and assign each key-value pair to the appropriate split dictionary based on its value.

for key, value in my_dict.items():
split_dicts[value][key] = value

This code assigns the key-value pair to the split dictionary with the corresponding value.

Step 4: Print the Split Dictionaries

Finally, we can print each split dictionary to see the result.

for value, split_dict in split_dicts.items():
print(f"Dictionary with value {value}: {split_dict}")

This code will print each split dictionary separately along with its corresponding value.

Complete Example

my_dict = {
'apple': 10,
'banana': 12,
'orange': 9,
'grape': 10,
'kiwi': 12,
'pineapple': 9
}

unique_values = set(my_dict.values())
split_dicts = {value: {} for value in unique_values}

for key, value in my_dict.items():
split_dicts[value][key] = value

for value, split_dict in split_dicts.items():
print(f"Dictionary with value {value}: {split_dict}")

Output

The output of the above code will be:

Dictionary with value 10: {'apple': 10, 'grape': 10}
Dictionary with value 12: {'banana': 12, 'kiwi': 12}
Dictionary with value 9: {'orange': 9, 'pineapple': 9}

The original dictionary has been split into three separate dictionaries based on the values. Each split dictionary contains the keys and values that match a specific value from the original dictionary.

That's it! You have successfully split a Python dictionary into multiple dictionaries based on values.