Skip to main content

How to convert a dictionary to a dictionary of unique values and their counts in Python

How to convert a dictionary to a dictionary of unique values and their counts in Python.

Here is a step-by-step tutorial on how to convert a dictionary to a dictionary of unique values and their counts in Python:

Step 1: Create a dictionary

First, let's start by creating a dictionary with some sample data. For this tutorial, let's assume we have a dictionary called my_dict:

my_dict = {"apple": 5, "banana": 3, "orange": 2, "kiwi": 5, "mango": 1}

Step 2: Initialize an empty dictionary

Next, we need to initialize an empty dictionary called unique_dict that will store the unique values and their counts:

unique_dict = {}

Step 3: Iterate over the dictionary

Now, we need to iterate over the items in the original dictionary using a for loop. For each key-value pair in my_dict, we will check if the value already exists as a key in unique_dict.

for key, value in my_dict.items():
if value in unique_dict:
unique_dict[value] += 1
else:
unique_dict[value] = 1

Step 4: Print the resulting dictionary

Finally, we can print the resulting unique_dict to see the unique values and their counts:

print(unique_dict)

The output will be:

{5: 2, 3: 1, 2: 1, 1: 1}

This means that there are two unique values with a count of 5, one unique value with a count of 3, one unique value with a count of 2, and one unique value with a count of 1.

Complete code example:

my_dict = {"apple": 5, "banana": 3, "orange": 2, "kiwi": 5, "mango": 1}
unique_dict = {}

for key, value in my_dict.items():
if value in unique_dict:
unique_dict[value] += 1
else:
unique_dict[value] = 1

print(unique_dict)

This is how you can convert a dictionary to a dictionary of unique values and their counts in Python. Feel free to customize the code according to your specific requirements.