Sometimes you may need to look for an item in a list of dictionaries in python. In this article, we will look at couple of ways to search item in list of dictionaries in Python.
How to Search Item in List of Dictionaries in Python
Here are couple of ways to search item in list of dictionaries in python. Let us say you have the following dictionary.
>>> data=[{'name':'Joe','age':20},{'name':'Tim','age':25},{'name':'Jim','age':30}] >>> data [{'age': 20, 'name': 'Joe'}, {'age': 25, 'name': 'Tim'}, {'age': 30, 'name': 'Jim'}]
1. Using loop
The most basic way to search an item based on key, value combination is to loop through each item and return the dictionary once it is found. Here is an example where we look for dictionary containing name = Jim
>>> for i in data: if i['name']=='Jim': print i {'age': 30, 'name': 'Jim'}
2. Using next() & dictionary comprehension
You can also achieve the above output using dictionary comprehension and next() function.
>>> res = next((sub for sub in data if sub['name'] == 'Jim'), None) >>> res {'age': 30, 'name': 'Jim'}
In the above article, we have looked at how to search a dictionary for value and return it. You may modify and use it according to your requirement.
Also read :
How to Remove Multiple Items from List in Python
How to Flatten List of Dictionaries in Python
How to Flatten List of Tuples in Python
How to Find & Delete Broken Symlinks
How to Remove Duplicates from List in Python
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.