KidSudi
KidSudi

Reputation: 492

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]}]

Upvotes: 6

Views: 106

Answers (3)

Kaustav Datta
Kaustav Datta

Reputation: 403

def return_dict(lst):
    for item in lst:
       if isinstance(item,dict) and 'k' in item:
          return item
    raise Exception("Item not found")

Upvotes: 6

PdevG
PdevG

Reputation: 3677

If you don't mind being a bit ugly in your code I would iterate through the list and check each element. Example:

def find_dict(lst):
    for element in lst:
        if type(element) == dict:
            if 'k' in element.keys():
                return element

There should be a more pythonic way for this probably.

Upvotes: 0

eumiro
eumiro

Reputation: 212835

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)

Upvotes: 7

Related Questions