Skip to main content

How to convert a dictionary to a dictionary of unique key-value pairs and their counts in Python

How to convert a dictionary to a dictionary of unique key-value pairs and their counts in Python.

Here's a step-by-step tutorial on how to convert a dictionary to a dictionary of unique key-value pairs and their counts in Python:

  1. Start by creating a dictionary with some key-value pairs. Let's call it original_dict. Here's an example:
original_dict = {'apple': 3, 'banana': 2, 'orange': 5, 'grape': 3, 'kiwi': 1}
  1. Initialize an empty dictionary to store the unique key-value pairs and their counts. Let's call it unique_dict.
unique_dict = {}
  1. Iterate over the items in the original_dict using a for loop. For each key-value pair, check if the key already exists in the unique_dict.

  2. If the key doesn't exist, add it as a new key in unique_dict and set its value to 1.

  3. If the key already exists, increment its value by 1.

Here's the complete code that implements the above steps:

original_dict = {'apple': 3, 'banana': 2, 'orange': 5, 'grape': 3, 'kiwi': 1}
unique_dict = {}

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

After executing the above code, the unique_dict will contain the unique key-value pairs and their counts. In this example, unique_dict will be:

{'apple': 1, 'banana': 1, 'orange': 1, 'grape': 1, 'kiwi': 1}

If you want to see the counts of the original values in the original_dict, you can modify the code slightly to store the counts instead of 1. Here's an example:

original_dict = {'apple': 3, 'banana': 2, 'orange': 5, 'grape': 3, 'kiwi': 1}
unique_dict = {}

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

After executing this modified code, unique_dict will be:

{'apple': 3, 'banana': 2, 'orange': 5, 'grape': 6, 'kiwi': 1}

That's it! You have successfully converted a dictionary to a dictionary of unique key-value pairs and their counts in Python.