Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max key in dictionary

Tags:

python

I have a dictionary that looks like this

MyCount= {u'10': 1, u'1': 2, u'3': 2, u'2': 2, u'5': 2, u'4': 2, u'7': 2, u'6': 2, u'9': 2, u'8': 2} 

I need highest key which is 10 but i if try max(MyCount.keys()) it gives 9 as highest.
Same for max(MyCount).

The dictionary is created dynamically.

like image 911
Chris Avatar asked Jun 24 '10 07:06

Chris


People also ask

How do you find the maximum key in a dictionary?

By using max() and dict. get() method we can easily get the Key with maximum value in a dictionary. To obtain the maximum value from the dictionary we can use the in-built max() function. In this example, we can use iterable and dict to get the key paired with the maximum value.

Can you use Max on a dictionary Python?

The simplest way to get the max value of a Python dictionary is to use the max() function. The function allows us to get the maximum value of any iterable.

What is key in max function Python?

key (optional) It refers to the single argument function to customize the sort order. The function is applied to each item on the iterable. If max() is called with an iterable, it returns the largest item in it. If the iterable is empty then the default value is returned, otherwise, a ValueError exception is raised.


1 Answers

This is because u'9' > u'10', since they are strings.

To compare numerically, use int as a key.

max(MyCount, key=int) 

(Calling .keys() is usually unnecessary)

like image 169
kennytm Avatar answered Sep 18 '22 15:09

kennytm