How to use list comprehension In Python
The list is simply iterated using list comprehension and the dictionaries are printed.
Example: Extracting keys using list comprehension
Python3
# Create a list of dictionaries languages = [ { "Python" : "Machine Learning" , "R" : "Machine learning" , }, { "Python" : "Web development" , "Java Script" : "Web Development" , "HTML" : "Web Development" }, { "C++" : "Game Development" , "Python" : "Game Development" }, { "Java" : "App Development" , "Kotlin" : "App Development" } ] # here we are printing the keys of the dictionary # by using list comprehension and each key will be # printed in a new line due to the presence of " sep = "\n" ". # It will add a new line character to our output. print ( * [key for i in languages for key in i.keys()], sep = "\n" ) |
Output:
Python
R
Python
Java Script
HTML
C++
Python
Java
Kotlin
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries.
List of dictionaries in use:
[{‘Python’: ‘Machine Learning’, ‘R’: ‘Machine learning’},
{‘Python’: ‘Web development’, ‘Java Script’: ‘Web Development’, ‘HTML’: ‘Web Development’},
{‘C++’: ‘Game Development’, ‘Python’: ‘Game Development’}, {‘Java’: ‘App Development’, ‘Kotlin’: ‘App Development’}]