Python:根据键的值在数组中查找字典

den*_*icz 1 python dictionary list

这是我的数组 dicts

[{'task': 'send-email', 'email': {'id': 1234}},
{'task': 'send-alert', 'email': {'id': 4567}}]
Run Code Online (Sandbox Code Playgroud)

我有一个方法:

def get_side_effect(self, type):
Run Code Online (Sandbox Code Playgroud)

我通过每个试图循环dict数组中,并找到dict其中的task密钥包含传递到方法的类型的值。

the*_*eye 6

def get_side_effect(self, key):
    return [cdict for cdict in my_list if cdict["task"] == key]

print obj.get_side_effect("send-email")
Run Code Online (Sandbox Code Playgroud)

输出

[{'task': 'send-email', 'email': {'id': 1234}}]
Run Code Online (Sandbox Code Playgroud)

建议不要将您的变量命名为type,因为这会影响内置type函数。

但是,如果您要做的只是迭代结果,则可以简单地执行此操作

for mathched_dict in (cdict for cdict in my_list if cdict["task"] == key):
    print mathched_dict
Run Code Online (Sandbox Code Playgroud)

或者您可以使用内置list函数将其转换为列表,如下所示

list(cdict for cdict in my_list if cdict["task"] == key)
Run Code Online (Sandbox Code Playgroud)