Python - Compare elements of keys in a dictionary and return one of the keys -


i trying compare elements in keys in dictionary. first compare first elements of keys, , if there more 1 highest value compare second element in keys.

for example:

>>> my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 77]} 

1) search first elements highest value. result should be:

('111', '122') 

2) search second elements of '111' , '112' lowest value. result should be:

('111') 

i found this discussion find key max value. 1 solution return multiple keys have same max is:

>>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} >>> [key key,val in stats.iteritems() if val == max(stats.values())] ['b', 'd'] 

the problem here these keys have 1 element. need figure out how keys multiple elements.

i suppose can return first elements of each key this:

>>> [item[0] item in my_dict.values()] ['50', '50', '40', '20'] 

but how compare them? in advance help!

using example dict, appears me following suit definition

>>> stats = {'a':[1,2,3], 'b':[2,8,9], 'c': [3,4,5], 'd':[5,6,8]} >>> [key key,val in stats.items() if sum(val) == max([sum(i) in stats.values()])] ['b', 'd'] 

and comparison or whatsoever. however, wouldn't recommend using dict these kinds of comparisons dicts inherently unordered. if possible, recommend usage or sorted(list, key) method generate ordered list comparison.


Comments