从字典列表中找到一个英雄



我有这个字典列表:

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

我需要在位置[1]中获得'campo:LinkState'的值,但我无法通过位置获得值,因为它变化…所以,也许我可以在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

使用filternext:

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'

如果缺少键或没有找到值,则应该返回None。

如果没有字典匹配,则设置默认值:

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

相关内容

最新更新