Search a value in a list of dictionaries in Python
This post will discuss how to search a value for a given key in a list of dictionaries in Python.
1. Using filter() function
The filter() is a built-in function that returns an iterator of items from an iterable that satisfy a given condition. We can use this function to search for a value in a list of dictionaries by passing a lambda expression that checks if the value matches one or more of the dictionary’s values as the first argument and the list of dictionaries as the second argument. For example:
|
1 2 3 4 5 6 7 8 9 10 11 |
dicts = [ {'lang': 'Java', 'version': '14'}, {'lang': 'Python', 'version': '3.8'}, {'lang': 'C++', 'version': '17'}, ] key = 'lang' val = 'Python' d = next(filter(lambda d: d.get(key) == val, dicts), None) print(d) # {'lang': 'Python', 'version': '3.8'} |
2. Using Generator Expression
Another solution is to use a generator expression for searching a value for a given key in a list of dictionaries. This would translate to a simple code below:
|
1 2 3 4 5 6 7 8 9 10 11 |
dicts = [ {'lang': 'Java', 'version': '14'}, {'lang': 'Python', 'version': '3.8'}, {'lang': 'C++', 'version': '17'}, ] key = 'lang' val = 'Python' d = next((d for d in dicts if d.get(key) == val), None) print(d) # {'lang': 'Python', 'version': '3.8'} |
3. Using for loop
We can use a for loop to search for a value in a list of dictionaries by looping over the list and checking if the value matches one or more of the dictionary’s values. For example, we can search for the value ‘Python’ in the list of dictionaries using a for loop like this:
|
1 2 3 4 5 6 7 8 9 10 11 |
dicts = [ {'lang': 'Java', 'version': '14'}, {'lang': 'Python', 'version': '3.8'}, {'lang': 'C++', 'version': '17'}, ] val = 'Python' for di in dicts: if val in di.values(): print(di) |
That’s all about searching for a value in a list of dictionaries in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)