![]() |
The dictionary is a collection of data items in the key-value pair and represented by the braces { }. The list is also a data type used to store the date and represented by the braces [ ]. The built-in Python method items() are used to retrieve all the keys and corresponding values. We can print the dictionary’s keys and values by combining the items() method with a for loop. Print All Values Of A Given Key Of Dictionaries In A ListBelow are some of the ways by which we can print all values of a given key of dictionaries in a list in Python:
Using for LoopThe for loop iterates the dictionaries present in the list. If the condition checks whether the given key is present in the dictionary or not. If it is present in the dictionary, then it will return the value of the key. If it is not present in the dictionary, it will not print anything. Python3
Output
['improvement', 'horje', 'author'] Using List ComprehensionHere, we are checking whether entered key is present in dictionary or not using list comprehension method and return the value of the key if exist in the dictionary. Python3
Output
['Hyderabad', 'United states', 'Japan'] Using the lambda and filter functionsThe filter() function filters the dictionaries in list of dictionaries where key is present. map() function retrieve the value of the key from each dictionary and result of map function is converted in to list using list() function. Python3
Output
['improvement', 'horje', 'author'] Using the operator moduleIn this example, itemgetter(desired_key) creates a callable object that extracts the value associated with the specified key from a dictionary. The map() function applies this callable to each dictionary in list_of_dicts, and the result is converted to a list. Python3
Output
[10, 30, 50] |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |