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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With