Skip to main content

How to convert a dictionary to a dictionary of unique keys in Python

How to convert a dictionary to a dictionary of unique keys in Python.

Here's a detailed step-by-step tutorial on how to convert a dictionary to a dictionary of unique keys in Python.

Step 1: Start by defining a dictionary that you want to convert. Let's call it original_dict. Make sure it contains some duplicate keys.

original_dict = {'apple': 5, 'banana': 2, 'apple': 3, 'orange': 4}

Step 2: Create an empty dictionary to store the unique keys. Let's call it unique_dict.

unique_dict = {}

Step 3: Iterate over the items in the original_dict using a for loop.

for key, value in original_dict.items():

Step 4: Check if the key already exists in the unique_dict. If it does not exist, add the key-value pair to the unique_dict.

if key not in unique_dict:
unique_dict[key] = value

Step 5: After the loop finishes, the unique_dict will contain only the unique keys and their corresponding values.

Step 6: Optional: Print the unique_dict to verify the results.

print(unique_dict)

Here's the complete code:

original_dict = {'apple': 5, 'banana': 2, 'apple': 3, 'orange': 4}
unique_dict = {}

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

print(unique_dict)

Output:

{'apple': 5, 'banana': 2, 'orange': 4}

That's it! You have successfully converted a dictionary to a dictionary of unique keys in Python.