i have this list of dicts:
[{'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'}]
i need to get the valor of 'campo:LinkState' that is in the position [1], but I can not get the value through the position because it varies... So, maybe can i do something like method .find
in Js but in python?
something like this :
var statusOnt = data.find(data=>data.campo=='LinkState');
but in python. thanks
CodePudding user response:
Why don't you just iterate over the list
?
for index, value in enumerate(my_list):
if (value['campo'] == 'LinkState'):
# index is the index you wanted
break
To better understand my code I would suggest you to read enumerate
docs.
If you want your code to be even more safe from KeyError
s and IndexError
s you can add a try
/catch
block:
try:
if (value['campo'] ...):
...
except KeyError:
continue
CodePudding user response:
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)
output: 'enable'
This should return None if any key is missing or value is not found.
If you want to set a default value if no dictionary matches:
out = next(filter(lambda d: d.get('campo', None)=='LinkState', l),
{'valor': 'default no match'}
).get('valor', 'default match but no defined value')