简体   繁体   English

使用它们的键从字典列表中获取值

[英]getting values from list of dictionaries using their key

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'.我想要做的是获取与外键匹配的每个元素的距离值,在本例中为“500”。

if key == 500: Then print the distance, something like that. if key == 500:然后打印距离,类似的东西。

Any help would be appreciated.任何帮助,将不胜感激。 This is not a duplicate of another post, I tried all the solutions available here, but I failed.这不是另一个帖子的重复,我尝试了所有可用的解决方案,但我失败了。

Use a simple for loop:使用一个简单的 for 循环:

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:如果您确定所有字典中都存在键500 ,它将为您提供所有距离的列表:

[e[500]['distance'] for e in my_list]

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM