How to convert a dictionary to a dictionary of unique values in Python
How to convert a dictionary to a dictionary of unique values in Python.
Here's a detailed step-by-step tutorial on how to convert a dictionary to a dictionary of unique values in Python.
Step 1: Create a sample dictionary
First, let's create a sample dictionary to work with. This dictionary will contain some duplicate values.
original_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value1', 'key4': 'value3'}
In this example, the values 'value1' and 'value3' are duplicated.
Step 2: Create an empty dictionary to store unique values
Next, we need to create an empty dictionary to store the unique values from the original dictionary.
unique_dict = {}
Step 3: Iterate over the original dictionary
Now, let's iterate over the key-value pairs of the original dictionary using a for loop.
for key, value in original_dict.items():
# Code to be added in the next step
Step 4: Check if the value is already present in the unique dictionary
Inside the for loop, we need to check if the current value is already present in the unique dictionary. If it is not present, we can add it.
for key, value in original_dict.items():
if value not in unique_dict.values():
unique_dict[key] = value
Here, if value not in unique_dict.values(): checks if the value is already present in the unique_dict. If it is not present, the key-value pair is added to the unique_dict.
Step 5: Print the unique dictionary
Finally, let's print the unique dictionary to see the result.
print(unique_dict)
Complete code example
Here's the complete code example that puts all the steps together:
original_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value1', 'key4': 'value3'}
unique_dict = {}
for key, value in original_dict.items():
if value not in unique_dict.values():
unique_dict[key] = value
print(unique_dict)
Output
When you run the above code, you will get the following output:
{'key1': 'value1', 'key2': 'value2', 'key4': 'value3'}
In the output, the key-value pair 'key3': 'value1' is not present because it was a duplicate value.
That's it! You have successfully converted a dictionary to a dictionary of unique values in Python.