Python is a powerful and versatile programming language that is widely used in a variety of fields. One of its powerful features is its ability to handle complex data structures like dictionaries.
Dictionaries in Python store key-value pairs where each key is unique. Sometimes, we might need a way to print all the unique values in a given dictionary. This tutorial will guide you through the steps of doing just that.
Step 1: Set Up a Python Dictionary
First, we will start by setting up a Python dictionary. For this example, let’s take a dictionary that has subject names as keys and their corresponding scores as values. smalldict can be your variable name for this dictionary.
1 2 3 4 5 6 |
smalldict = { "maths": 90, "english": 80, "science": 100, "history": 80 } |
Step 2: Define a Function to Retrieve Unique Values
Now, we have to create a function that goes through all the values in the dictionary and removes the duplicates. For this task, we will use the built-in Python function set(). The Set is a built-in Python data type that automatically stores only unique values.
1 2 |
def unique_values(dictionary): return set(dictionary.values()) |
Step 3: Call the Function and Print Unique Values
Lastly, we will call the function that we defined previously and print the unique values returned by the function.
1 2 |
uniqueVal = unique_values(smalldict) print(uniqueVal) |
The Full Python Code
When we put all the code snippets together, the complete Python program would look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
smalldict = { "maths": 90, "english": 80, "science": 100, "history": 80 } def unique_values(dictionary): return set(dictionary.values()) uniqueVal = unique_values(smalldict) print(uniqueVal) |
Output
{80, 90, 100}
As we can see from the output, our Python code has successfully returned the unique values from the smalldict dictionary: 80, 90, and 100.
Conclusion
Python’s powerful data structures and inbuilt functions offer easy and efficient ways to tackle data manipulation tasks. In this tutorial, we saw how to print unique values in a Python dictionary using the set built-in function which automatically handles duplicate checks.
The unique_values function created in this tutorial can be extended to any dictionary to print unique values. Happy programming!