20

I'm using Python's max function to find the largest integer in a dictionary called count, and the corresponding key (not quite sure if I'm saying it properly; my code probably explains itself better than I'm explaining it). The dictionary count is along the lines of {'a': 100, 'b': 210}, and so on.

number = count[max(count.items(), key=operator.itemgetter(1))[0]]
highest = max(count, key=count.get)

What would I do if there were two equal largest values in there? If I had {'a': 120, 'b': 120, 'c': 100}, this would only find the first of a and b, not both.

vaultah
  • 44,105
  • 12
  • 114
  • 143
kidosu
  • 383
  • 2
  • 4
  • 9
  • 1
    What you do seems overly complex. Fox example: `number = max(count.values())`. – Lev Levitsky Mar 24 '12 at 16:31
  • I can't resist one-liners for these kinds of questions `highest, number = reduce(lambda a, b:a[0].append(b[0]) or (a[0], b[1]) if b[1] == a[1] else (([b[0]], b[1]) if b[1] > a[1] else a), count.iteritems(), ([], -1))` – Michael Mior Mar 24 '12 at 17:38

6 Answers6

32

Idea is to find max value and get all keys corresponding to that value:

count = {'a': 120, 'b': 120, 'c': 100}

highest = max(count.values())

print([k for k, v in count.items() if v == highest])
vaultah
  • 44,105
  • 12
  • 114
  • 143
Asterisk
  • 3,534
  • 2
  • 34
  • 53
  • Could you explain a little regarding what Python's doing here? I'm quite new to it. – kidosu Mar 24 '12 at 17:55
  • 1
    1. count.values() returns list of values, e.g. [120, 120, 100]. 2. max(count.values()) returns a max value from list, e.g. 120. 3. count.items() returns a list of (key, value) tuples, e.g. [('a', 120), ('b', 120), ('c', 100)]. The last line is called list comprehension. You can rewrite the same code as follows. Iterate through (key, value) pairs in the dictionary, and if value is the same as highest, then add key to a list. – Asterisk Mar 24 '12 at 17:57
  • Thank you! Is there any way not to print the brackets? – kidosu Mar 24 '12 at 17:58
  • Could this same code be applied if instead 'a','b' and 'c' were columns of a data frame? – CJJ Oct 05 '20 at 22:44
2

Same idea as Asterisk, but without iterating over the list twice. Bit more verbose.

count = { 'a': 120, 'b': 120, 'c': 100 }
answers = []
highest = -1

def f(x):
    global highest, answers
    if count[x] > highest:
        highest = count[x]
        answers = [x]
    elif count[x] == highest:
        answers.append(x)

map(f, count.keys())
print answers
Jos Kraaijeveld
  • 229
  • 2
  • 11
1

Fast single pass:

a = { 'a': 120, 'b': 120, 'c': 100 }
z = [0]
while a:
    key, value = a.popitem()
    if value > z[0]:
        z = [value,[key]]
    elif value == z[0]:
        z[1].append(key)

print z
#output:
[120, ['a', 'b']]

And an amusing way with defaultdict:

import collections
b = collections.defaultdict(list)
for key, value in a.iteritems():
    b[value].append(key)
print max(b.items())
#output:
(120, ['a', 'b'])
Christian K.
  • 2,785
  • 18
  • 40
fraxel
  • 34,470
  • 11
  • 98
  • 102
  • As an intermediate result you have a map of (value -> [keys]) for all values. This fact (additional data structures) makes it quite slow (but quite elegant). – Tupteq Mar 24 '12 at 17:38
0

This could be a way (probably not the most efficient).

value = max(count.values())
filter(lambda key: count[key]==value,count)
luke14free
  • 2,529
  • 1
  • 17
  • 25
0

Sometimes simplest solution may be the best:

max_value = 0
max_keys = []

for k, v in count.items():
    if v >= max_value:
        if v > max_value:
            max_value = v
            max_keys = [k]
        else:
            max_keys.append(k)

print max_keys

The code above is slightly faster than two pass solution like:

highest = max(count.values())
print [k for k,v in count.items() if v == highest]

Of course it's longer, but on the other hand it's very clear and easy to read.

Tupteq
  • 2,986
  • 1
  • 21
  • 30
  • I forgot to mention - this is a Python 3.x solution, it you are using Python 2.x, you should replace count.items() by count.iteritems(). – Tupteq Mar 24 '12 at 17:32
  • Worth nothing that `count.items()` will work in Python 2.x as well (albeit not as efficiently). – Michael Mior Mar 24 '12 at 17:39
-1

To print a list without bucket. use :

' '.join(map(str, mylist))

or, more verbosely:

' '.join(str(x) for x in mylist)
Ray
  • 1,647
  • 13
  • 16