How to convert a dictionary to a dictionary of unique values and their frequencies in Python
How to convert a dictionary to a dictionary of unique values and their frequencies in Python.
Here's a detailed step-by-step tutorial on how to convert a dictionary to a dictionary of unique values and their frequencies in Python.
Step 1: Create a dictionary
First, let's start by creating a dictionary with some sample data. This dictionary can contain any key-value pairs you want. For this tutorial, let's create a dictionary called original_dict.
original_dict = {'apple': 2, 'banana': 3, 'orange': 2, 'grape': 1, 'kiwi': 3}
Step 2: Initialize an empty dictionary
Next, we need to initialize an empty dictionary that will store the unique values and their frequencies. Let's call this dictionary unique_dict.
unique_dict = {}
Step 3: Iterate through the original dictionary
Now, we need to iterate through each key-value pair in the original_dict using a for loop. For each iteration, we'll check if the value already exists as a key in the unique_dict. If it does, we'll increment the frequency count. If it doesn't, we'll add the value as a key in the unique_dict with a frequency count of 1.
for key, value in original_dict.items():
if value in unique_dict:
unique_dict[value] += 1
else:
unique_dict[value] = 1
Step 4: View the result
To see the final result, you can print the unique_dict dictionary. This will display the unique values as keys and their corresponding frequencies as values.
print(unique_dict)
Step 5: Complete code example
Here's the complete code example that you can run:
original_dict = {'apple': 2, 'banana': 3, 'orange': 2, 'grape': 1, 'kiwi': 3}
unique_dict = {}
for key, value in original_dict.items():
if value in unique_dict:
unique_dict[value] += 1
else:
unique_dict[value] = 1
print(unique_dict)
This will output:
{2: 2, 3: 2, 1: 1}
In this example, the unique values '2', '3', and '1' from the original_dict dictionary are the keys in the unique_dict, and their corresponding frequencies are the values.
You can modify the original_dict with your own data and the code will still work the same way. You can also use this code as a function and pass your dictionary as an argument to convert it to a dictionary of unique values and their frequencies.