Get max key in dictionary
Question:
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.
Answers:
max(map(int, MyCount))
Or if you want the return value to be the original string:
max(MyCount, key=int)
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)
Since your keys are strings, they are compared lexicographically and ‘9’ is the max value indeed.
What you are looking for is something like:max(int(k) for k in MyCount)
This is your problem:
>>> u'10' > u'9'
False
Effectively, you’re comparing the characters ‘1’ and ‘9’ here. What you want is probably this:
max(long(k) for k in MyCount)
or create the dictionary with numbers as keys (instead of strings).
You use max for string values. You must convert them to int. Try something like:
print(max([int(s) for s in MyCount.keys()]))
Or as Tim suggested:
print(max(int(s) for s in MyCount))
You need to compare the actual numerical values. Currently you’re comparing the strings lexigraphically.
max(MyCount, key=int)
In case anybody ended up here looking for how to sort by value instead of the key:
max(MyCount, key=MyCount.get)
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.
max(map(int, MyCount))
Or if you want the return value to be the original string:
max(MyCount, key=int)
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)
Since your keys are strings, they are compared lexicographically and ‘9’ is the max value indeed.
What you are looking for is something like:max(int(k) for k in MyCount)
This is your problem:
>>> u'10' > u'9'
False
Effectively, you’re comparing the characters ‘1’ and ‘9’ here. What you want is probably this:
max(long(k) for k in MyCount)
or create the dictionary with numbers as keys (instead of strings).
You use max for string values. You must convert them to int. Try something like:
print(max([int(s) for s in MyCount.keys()]))
Or as Tim suggested:
print(max(int(s) for s in MyCount))
You need to compare the actual numerical values. Currently you’re comparing the strings lexigraphically.
max(MyCount, key=int)
In case anybody ended up here looking for how to sort by value instead of the key:
max(MyCount, key=MyCount.get)