0 votes
1 view
in Python by (1.6k points)

 I have a dictionary: keys are strings, values are integers.

Example:

stats = {'p':4000, 'q':8000, 'r': 900}

I'd like to get 'q' as an answer, since it's the key with a higher value.

I did the following, using an intermediate list with reversed key-value tuples:

inverse = [(value, key) for key, value in stats.items()]

print max(inverse)[1]

Is that one the better (or even more elegant) approach? 

2 Answers

0 votes
by (10.9k points)
edited by

You can use the operator.itemgetter(items) ,it returns a callable object which fetches item from its operand using _getitem_() method of the operand.

To use operator.itemgetter() use this code:

import operator

stats = {'p':4000, 'q':8000, 'r': 900}

max(stats.iteritems(), key=operator.itemgetter(1))[0]

In the above max() function, you have the “key” parameter is a function which compares elements to find the maximum between them. You may also use stats.iteritems() since it minimizes the memory use by eliminating the need for creating a new list.

Note:

In case you have:

stats = {'p':4000, 'q':8000, 'r': 900,‘s’:8000}

Then don’t expect the function to return both the maximum values ‘q’ and ‘s’,it will only return either of the two i.e, either ‘q’ or ‘s’ and not both.

Ex-

>>> import operator

>>> stats = {'p':4000, 'q':8000, 'r': 900,‘s’:8000}

>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]

's’

For Python 3, replace stats.iteritems() with stats.items().

Hope this helps!

 

0 votes
by (20.3k points)

You can try using the code given below:

max(stats, key=stats.get)

OR

You can just try doing this:

stats = {'a':1000, 'b':3000, 'c': 100}

max(stats.iterkeys(), key=lambda k: stats[k])

Here, the function key simply returns the value that should be used for ranking and max() returns the demanded element right away.

Related questions

0 votes
1 answer
asked Jul 3, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
+1 vote
1 answer
asked Jul 5, 2019 in Python by selena (1.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...