简体   繁体   中英

Sort a dictionary that was stored in anther dictionary by values and return the key based on condition

the dictionary structure is:

info ={'car1':{'location':10,'speed':10},
       'car2':{'location':5,'speed':20},
       'car3':{'location':1,'speed':5},
       'car4':{'location':50,'speed':30},
       ...}

Now, I want to get all cars' speed information and sort the speed list. Then, find the car which has the faster speed like this:

speed_list = [30,20,10,5]
fastest car: car4

dict.values()can get the dictionary values and max(dict, dict.get) can get the key with the biggest value, but they are not available in my case.

max(info, info.get)
'>' not supported between instances of 'dict' and 'dict'

max(info.values(), info.values.get)
'dict_values' object has no attribute 'get'

What should I do to get the list and the car number with the biggest speed?

There are a million ways to do this, here's just one.

  • Use.items() in a build a sequence of (speed, car_name) pairs.
  • Sort it (here, calling sorted on a generator expression, but sort would work if this line were split over two, and genexp replaced with a list comprehension)
  • Use a list comprehension to get the first element of these pairs -> speed_list .
  • Get the second element of the first of these pairs (since the list of pairs is sorted in descending order, the first element will be (one of) the car(s) with the fastest speed) -> fastest_car
info = {'car1':{'location':10,'speed':10},
        'car2':{'location': 5,'speed':20},
        'car3':{'location': 1,'speed': 5},
        'car4':{'location':50,'speed':30}
}

cars = sorted(((v['speed'], k) for (k,v) in info.items()), reverse=True)
# or:
#   cars = [(v['speed'], k) for (k,v) in info.items()]
#   cars.sort(reverse=True)
speed_list = [s for (s,_) in cars]
_, fastest_car = cars[0]

print(speed_list)    # [30, 20, 10, 5]
print(fastest_car)   # 'car4'

To get the fastest car:

fastest_car = max(info, key=lambda car: info[car]['speed'])

Another way to get the speed list:

speed_list = sorted((d['speed'] for d in info.values()), reverse=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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