Python program to extract unique values from the dictionary

Here, we are going to learn how to extract all unique values from the key-value pairs of the dictionary in Python?
Submitted by Shivang Yadav, on March 25, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

In a dictionary, the keys need to be unique but the values mapped can have duplicate values.

Here, we need to print all the unique values from the dictionary.

We have a dictionary consisting of key-value pairs, with duplicate values. We will print all the unique values from the dictionary.

Example:

Dictionary =
['scala':1, 'Javascript': 7, 'Python':1, 'C++':5, 'Java':3]
Unique values = 
1, 7, 5, 3

To find all the unique values, we will extract all the values of the dictionary. Then to find unique values, we will use set comprehension. And store the unique values to a list using list().

Program to extract unique values from the dictionary

# Python program to shuffle dictionary Values...

# Initialising dictionary
myDict = {'Scala': 2, 'Javascript': 1, 'Python': 8, 'C++': 1, 'Java': 4}

# extracting unique values using set comprehension
uniqueValues = list({val for val in myDict.values() })
  
# Printing the dictionary and unique values...
print("Dictionary = ", end = " ")
print(myDict)
print("Unique Values = ", end = " ")
print(uniqueValues)

Output:

Dictionary =  {'C++': 1, 'Javascript': 1, 'Java': 4, 'Python': 8, 'Scala': 2}
Unique Values =  [8, 1, 2, 4]

Python Dictionary Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.