从字典列表中找到一个勇气

Find a valor from list of dict

我有这个字典列表:

l = [{'campo': 'Admin_state', 'valor': 'enable'},
     {'campo': 'LinkState', 'valor': 'enable'},
     {'campo': 'ONU_interface', 'valor': 'gpon-onu_1/2/15:31'},
     {'campo': 'Profile_type_Ont', 'valor': 'ZTE-F660V3'}]

我需要获得 'campo:LinkState' 位置 [1] 的勇气,但我无法通过该位置获得价值,因为它会变化...所以,也许我可以做类似的事情Js 中的方法 .find 但在 python?

像这样:

var statusOnt = data.find(data=>data.campo=='LinkState');

但在 python。谢谢

为什么不直接遍历 list

for index, value in enumerate(my_list):
    if (value['campo'] == 'LinkState'):
        # index is the index you wanted
        break

为了更好地理解我的代码,我建议您阅读 enumerate 文档。


如果您希望您的代码在 KeyErrors 和 IndexErrors 中更加安全,您可以添加一个 try/catch 块:

try:
    if (value['campo'] ...):
        ...
except KeyError:
    continue

使用filter and next

l = [{'campo': 'Admin_state', 'valor': 'enable'},
     {'campo': 'LinkState', 'valor': 'enable'},
     {'campo': 'ONU_interface', 'valor': 'gpon-onu_1/2/15:31'},
     {'campo': 'Profile_type_Ont', 'valor': 'ZTE-F660V3'}]

out = next(filter(lambda d: d.get('campo', None)=='LinkState', l), {}
          ).get('valor', None)

输出:'enable'

如果缺少任何键或找不到值,这应该 return None。

如果没有匹配的字典你想设置一个默认值:

out = next(filter(lambda d: d.get('campo', None)=='LinkState', l),
           {'valor': 'default no match'}
           ).get('valor', 'default match but no defined value')