Finding highest/lowest key:value pair in python3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Finding highest/lowest key:value pair in python3

I have been able to get a dictionaries min/max values but how can I tell which key was used. https://code.sololearn.com/cSV3Oj95qOfk/?ref=app

5th Feb 2018, 3:02 AM
Kinkos
Kinkos - avatar
2 Answers
+ 5
# Basic solution, working for string keys, not for only number keys: # (when comparing two strings, '10' is considered as lower than '1' for example) keys = dict.keys() highest_key = max(keys) lowest_key = min(keys) print("highest key is %s" % highest_key) print("lowest key is %s" % lowest_key) # improved for working with only number keys: # (get list of keys, and sort by value converted to int) dict = { "10":10, "2":22, "3":-2, "4":-15, "5":-25 } keys = list(dict.keys()) keys.sort(key = int) highest_key = keys[0] lowest_key = keys[1] print("highest key is %s" % highest_key) print("lowest key is %s" % lowest_key) """ You could use any custom function (even a lambda one) to handle ordering string keys by alpha AND numeric by implementing some more advanced sort function (splitting string from last digits, and comparing both alphabetics and integer to get a customized order, to avoid following the default alphanumeric order -- based on character code -- and similary handle case proof ordering ^^) """
5th Feb 2018, 3:31 AM
visph
visph - avatar
+ 5
Oh, sorry : I've missunderstood your question ^^ To get the keys of particular value, you need to iterate over it, and search for value equality... assuming there's no duplicate values (same value at two different keys), or that's will return the first item reaching condition (equality), without knowing the order of iteration, unless you get the keys list and order it to have an explicit order (dict are not ordered data list structures)... https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary
5th Feb 2018, 3:36 AM
visph
visph - avatar