Reputation: 41
I have a list of dictionaries like below:
What I want to do, is to get the distance value of each element which matches the outer key, which in this case is '500'.
if key == 500:
Then print the distance, something like that.
Any help would be appreciated. This is not a duplicate of another post, I tried all the solutions available here, but I failed.
Upvotes: 0
Views: 93
Reputation: 16002
You can simplify this with list comprehension:
def get_distances(list_, key)
return [obj[key]['distance'] for obj in list_ if key in obj]]
get_distances(list_, 500)
Upvotes: 0
Reputation: 1186
Use a simple for loop:
for e in my_list:
if 500 in e:
print(e[500]["distance"])
If you are sure the key 500
is present in all dictionaries, it will give you a list of all the distances:
[e[500]['distance'] for e in my_list]
Upvotes: 1