-1

I am trying to compare elements in keys in a dictionary. I would like to first compare all first elements of the keys, and then if there are more than one with the highest value then compare the second element in those 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 for highest value. Result should be:

('111', '122')

2) Search second elements of '111' and '112' for lowest value. Result should be:

('111')

I found this discussion to find the key with the max value. One solution to return multiple keys that have the same max is:

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

The problem here is that these keys only have one element. I need to figure out how to do it for keys with multiple elements.

I suppose I can return the first elements of each key like this:

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

But then how do I compare them? Thanks in advance for your help!

Community
  • 1
  • 1
Ebad
  • 131
  • 11
  • If you don't care about the keys, `my_dict.values()` will give you a list of lists ( the values ) . You can then compare lists. – t.m.adam Apr 06 '17 at 03:47
  • You could do that with for loops, or functions like `cmp()`, `sum()`, etc , or external libraries like numpy . – t.m.adam Apr 06 '17 at 03:55

1 Answers1

1

using your example for dict, it appears me that the following would suit your definition

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

and then do your comparison or whatsoever. however, i wouldn't recommend using a dict for these kinds of comparisons as dicts are inherently unordered. if possible, i would recommend the usage or sorted(list, key) method to generate an ordered list for comparison.

  • That gets the sum of the elements and then finds the max of the sums. I need to find the max first element and then if there are more than one find the key with the min second element. I will look into doing it with a list. I liked having a key because it is a unique identifier for each entry. – Ebad Apr 06 '17 at 04:30