Extract Unique dictionary values in Python Program

PythonServer Side ProgrammingProgramming

When it is required to extract unique values from a dictionary, a dictionary is created, and the ‘sorted’ method and dictionary comprehension is used.

Below is a demonstration for the same −

Example

 Live Demo

my_dict = {'hi' : [5,3,8, 0],
   'there' : [22, 51, 63, 77],
   'how' : [7, 0, 22],
   'are' : [12, 11, 45],
   'you' : [56, 31, 89, 90]}

print("The dictionary is : ")
print(my_dict)

my_result = list(sorted({elem for val in my_dict.values() for elem in val}))

print("The unique values are : ")
print(my_result)

Output

The dictionary is :
{'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22], 'are': [12, 11, 45], 'you': [56, 31, 89, 90]}
The unique values are :
[0, 3, 5, 7, 8, 11, 12, 22, 31, 45, 51, 56, 63, 77, 89, 90]

Explanation

  • A dictionary is defined, and is displayed on the console.

  • The values of the dictionary are accessed using the ‘.values’ method.

  • It is converted into a list, and is assigned to a variable.

  • This is displayed as output on the console.

raja
Published on 17-Apr-2021 12:07:16
Advertisements