- 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
Python Program to get all unique keys from a List of Dictionaries
When it is required to get all the unique keys from a list of dictionary, the dictionary values are iterated over and converted into a set. This is converted to a list and displayed on the console.
Example
Below is a demonstration of the same
my_list = [{'hi' : 11, 'there' : 28}, {'how' : 11, 'are' : 31}, {'you' : 28, 'Will':31}] print("The list is:") print(my_list) my_result = list(set(value for dic in my_list for value in dic.values())) print("The result is :") print(my_result)
Output
The list is: [{'there': 28, 'hi': 11}, {'how': 11, 'are': 31}, {'Will': 31, 'you': 28}] The result is : [11, 28, 31]
Explanation
A list of dictionary values is defined and is displayed on the console.
It is iterated over, and only the ‘values’ of the dictionary are accessed.
It is converted to a set to retain only the unique values.
This is then converted to a list and assigned to a variable.
This is the output that is displayed on the console.
Advertisements