- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Unique dictionary values in Python Program
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
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.
Advertisements