I am trying to get the value (fcs
) when the key value is "Team"
. I tried with python code but was not able to get the value once the key is matched with "Team".
[{'key':'appid','value':'xyz'},{'key':'Team','value':'fcs'},{'key':'incident','value':'a1435621'}]
CodePudding user response:
Another solution, using next()
:
lst = [
{"key": "appid", "value": "xyz"},
{"key": "Team", "value": "fcs"},
{"key": "incident", "value": "a1435621"},
]
team = next(d["value"] for d in lst if d["key"] == "Team")
print(team)
Prints:
fcs
CodePudding user response:
Python dictionaries have the structure
dict = {
key1: value1,
key2: value2,
}
I would recommend changing your data structure into the form above rather than have an list of dictionaries. That way, your data will look like this
data = {
appleid:"xyz",
Team:"fcs",
incident:"a1435621"
}
That way, you can call your data like this
print(data.Team) #this will output "fcs"
If you still want to keep your original structure of data, you write a for loop that goes through each dictionary and once you find the one that matches, you can store the index and call it
index = 0
for i in range(0, len(data)):
if data[i].key == "Team":
index = i
print(data[i].value)