Skip to main content

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

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

Here is a step-by-step tutorial on how to convert a dictionary to a dictionary of unique key-value pairs in Python.

Step 1: Create a dictionary

First, you need to create a dictionary with multiple key-value pairs. Let's create a sample dictionary to work with:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'a': 4, 'd': 5, 'e': 6}

In this example, we have a dictionary with duplicate keys ('a') and some unique keys ('b', 'c', 'd', 'e').

Step 2: Create a function to convert the dictionary

Next, we will create a function that takes the original dictionary as input and returns a new dictionary with unique key-value pairs. Let's call this function convert_to_unique_dict. Here's how you can define the function:

def convert_to_unique_dict(dictionary):
unique_dict = {}
for key, value in dictionary.items():
unique_dict[key] = value
return unique_dict

This function creates an empty unique_dict and then iterates over each key-value pair in the original dictionary. It adds each key-value pair to the unique_dict.

Step 3: Call the function

Finally, you can call the convert_to_unique_dict function and pass your dictionary as an argument. It will return a new dictionary with unique key-value pairs. Here's how you can call the function with our sample dictionary:

unique_dict = convert_to_unique_dict(my_dict)

Now, unique_dict will contain the unique key-value pairs from my_dict.

Example

Let's put it all together with an example:

def convert_to_unique_dict(dictionary):
unique_dict = {}
for key, value in dictionary.items():
unique_dict[key] = value
return unique_dict

my_dict = {'a': 1, 'b': 2, 'c': 3, 'a': 4, 'd': 5, 'e': 6}
unique_dict = convert_to_unique_dict(my_dict)

print(unique_dict)

Output:

{'a': 4, 'b': 2, 'c': 3, 'd': 5, 'e': 6}

In this example, the original dictionary my_dict has two entries with the key 'a'. However, the converted dictionary unique_dict only contains the last occurrence of 'a' with the value 4.

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