I've found some similar questions but none has solved my problem. Follow this example:
d={'a': 6, 'b': 3, 'c': 8, 'd': 1}
Now I wanna print the key that has the greatest number (in this case 'c'
) and the smallest too (in this case 'd'
). Realize that what I wanna print is the key, not its value.
@Mateus, here is another way that doesn't use lambda functions:
d={'a': 6, 'b': 3, 'c': 8, 'd': 1}
# Solution #1 - Using lambda function
print('Min key =', min(d, key=lambda k: d[k]))
print('Max key =', max(d, key=lambda k: d[k]))
# Solution #2 - Using the dictionary get() method
print ('Min key =', min(d, key=d.get))
print ('Max key =', max(d, key=d.get))
Either approach will give the same result:
Min key = d
Max key = c
Min key = d
Max key = c
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.