-2

How can I extract the maximum value for each key in a dictionary of lists?

For example

#Generate some sample data
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

I would like to return the following results:

blue 4
red 1
yellow 3

I have unsuccessfully tried looping over the dictionary and extracting the list values. However, I cannot seem to find a way to extract the values and link them to the proper keys.

Borealis
  • 8,044
  • 17
  • 64
  • 112
  • @jonrsharpe Please note that I have addressed your comments in the post. – Borealis Sep 15 '14 at 17:58
  • Somewhat vaguely - a [minimal example](http://stackoverflow.com/help/mcve) and concise description of the problem (error traceback or input and expected and actual output) is helpful. – jonrsharpe Sep 15 '14 at 18:48

3 Answers3

4
for k, v in d.items():
    print k, max(v)
chishaku
  • 4,577
  • 3
  • 25
  • 33
3

If you don't need to keep around the list of all possible values, and just need the max, this will do it:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = dict(sorted(s))

d is now:

{'blue': 4, 'yellow': 3, 'red': 1}

The sorted(s) will sort the tuples in ascending order, and the dict constructor will only reflect the final (highest) result.

Bonus: If you want the minimum values, dict(sorted(s, reverse=True)) will give that to you:

{'blue': 2, 'red': 1, 'yellow': 1}
Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77
  • I believe this solution can be categorized under the “cool hacks” section. However, I don't see how it makes the code more readable or efficient. – 5gon12eder Sep 15 '14 at 20:37
  • 1
    @5gon12eder I have mixed feelings about it too. The "sort a list of tuples" idiom is like the Schwartzian transform and a lot of other sorting tricks: powerful, useful...and yet, still a bit of a trick. – Jonathan Eunice Sep 15 '14 at 21:57
1

If you want the results in a dictionary as well, you could use a one-liner generator expression.

items = {'blue': [2, 4], 'yellow': [1, 3], 'red': [1]}
maxitems = {k : max(items[k]) for k in items}
5gon12eder
  • 24,280
  • 5
  • 45
  • 92