0

I have a list of dictionaries like below:

enter image description here

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.

Laurits L. L.
  • 417
  • 1
  • 4
  • 15
  • 1
    Possible duplicate of [Getting a list of values from a list of dicts](https://stackoverflow.com/questions/7271482/getting-a-list-of-values-from-a-list-of-dicts) – bharatk Oct 03 '19 at 09:35
  • @bharatk no, it's not. i already used that but no luck. [d['500'] for d in list_of_dictionary] getting a keyError. or even with [d['distance'] for d in list_of_dictionary] – krunal patel Oct 03 '19 at 09:38
  • 2
    You should add a code sample that produces some actual output, and a sample of the output that you expected. – Kraay89 Oct 03 '19 at 09:40

2 Answers2

1

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]
Silveris
  • 1,048
  • 13
  • 31
  • 3
    It is not redundant... OP didn't tell if the dicts all have the key 500. And no, it will not be true if it is 5000. 500 is an integer, not a string. – Silveris Oct 03 '19 at 09:43
  • 3
    @KostasCharitidis it's not redundant. if '500' is not in the dictionairy it will raise a KeyError. Dictionary keys aren't evaluated as a string on a per-key basis, so 500 will never match 5000. – Kraay89 Oct 03 '19 at 09:45
  • @Silveris Yes, you're right, that solved my query. and stuck in another one if you can help. I have this list list_of_dictionary.append({test_index : {"train_index" : train_index, "distance" : distance, "class" : y_train[train_index-1]}}) what i want is to sort the list according to distance and get the 3 minimum values of a list along with the class attribute. How can i achieve that? – krunal patel Oct 03 '19 at 20:24
  • @krunalpatel Where is the list? – Silveris Oct 04 '19 at 09:16
0

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)
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80