Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuples and Dictionaries contained within a List

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]}]
like image 233
KidSudi Avatar asked Jan 12 '16 15:01

KidSudi


1 Answers

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)
like image 106
eumiro Avatar answered Oct 27 '22 00:10

eumiro