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.
sorted
on a generator expression, but sort
would work if this line were split over two, and genexp replaced with a list comprehension)speed_list
.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.