How to convert a dictionary to a dictionary of unique keys and their counts in Python
How to convert a dictionary to a dictionary of unique keys and their counts in Python.
How to Convert a Dictionary to a Dictionary of Unique Keys and Their Counts in Python
In Python, you can convert a dictionary to a dictionary of unique keys and their counts by following these steps:
- Define the input dictionary that you want to convert.
- Create an empty dictionary to store the unique keys and their counts.
- Iterate over the items in the input dictionary.
- For each key in the input dictionary, check if it already exists in the new dictionary.
- If the key exists in the new dictionary, increment the count for that key by 1.
- If the key does not exist in the new dictionary, add it with an initial count of 1.
- Repeat steps 4 to 6 for all keys in the input dictionary.
- Return the new dictionary containing the unique keys and their counts.
Here is an example implementation of the above steps:
def count_unique_keys(dictionary):
unique_dict = {}
for key in dictionary:
if key in unique_dict:
unique_dict[key] += 1
else:
unique_dict[key] = 1
return unique_dict
Let's test the function with an example:
my_dict = {'apple': 3, 'banana': 2, 'orange': 1, 'apple': 2, 'grape': 4}
result = count_unique_keys(my_dict)
print(result)
Output:
{'apple': 2, 'banana': 1, 'orange': 1, 'grape': 1}
In this example, the input dictionary my_dict contains multiple keys with duplicate entries. The count_unique_keys function converts it into a new dictionary result where each key represents a unique key from the input dictionary and its corresponding value represents the count of occurrences of that key.
The output dictionary result contains the unique keys and their counts as follows:
- 'apple': 2 (because it appeared twice in the input dictionary)
- 'banana': 1
- 'orange': 1
- 'grape': 1
You can use this technique to convert any dictionary into a dictionary of unique keys and their counts in Python.