列表中包含的元组和字典

Kid*_*udi 6 python dictionary tuples list

我试图从包含元组和词典的列表中获取特定的字典.我如何从下面的列表中返回带有键'k'的字典?

lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}]
Run Code Online (Sandbox Code Playgroud)

eum*_*iro 7

为您

lst = [('apple', 1), ('banana', 2), {'k': [1,2,3]}, {'l': [4,5,6]}]
Run Code Online (Sandbox Code Playgroud)

运用

next(elem for elem in lst if isinstance(elem, dict) and 'k' in elem)
Run Code Online (Sandbox Code Playgroud)

回报

{'k': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)

即列表中的第一个对象,它是一个字典,包含键"k".

StopIteration如果没有找到这样的对象,则会引发此问题.如果你想返回别的东西,例如None,使用这个:

next((elem for elem in lst if isinstance(elem, dict) and 'k' in elem), None)
Run Code Online (Sandbox Code Playgroud)


Kau*_*tta 6

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