I am trying to a obtain a specific dictionary from within a list that contains both tuples and dictionaries. How would I go about returning the dictionary with key 'k' from the list below?
lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}]
For your
lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}]
using
next(elem for elem in lst if isinstance(elem, dict) and 'k' in elem)
returns
{'k': [1, 2, 3]}
i.e. the first object of your list which is a dictionary and contains key 'k'.
This raises StopIteration
if no such object is found. If you want to return something else, e.g. None
, use this:
next((elem for elem in lst if isinstance(elem, dict) and 'k' in elem), None)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With