简体   繁体   English

获取字典中的最大键

[英]Get max key in dictionary

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.我需要 10 的最高键,但如果尝试max(MyCount.keys())它给出 9 作为最高。
Same for max(MyCount) . max(MyCount)

The dictionary is created dynamically.字典是动态创建的。

This is because u'9' > u'10' , since they are strings .这是因为u'9' > u'10' ,因为它们是strings

To compare numerically, use int as a key.要进行数字比较,请使用int作为键。

max(MyCount, key=int)

(Calling .keys() is usually unnecessary) (调用.keys()通常是不必要的)

You need to compare the actual numerical values.您需要比较实际数值。 Currently you're comparing the strings lexigraphically.目前,您正在按字典顺序比较字符串。

max(MyCount, key=int)
max(map(int, MyCount))

或者,如果您希望返回值是原始字符串:

max(MyCount, key=int)

Since your keys are strings, they are compared lexicographically and '9' is the max value indeed.由于您的键是字符串,因此按字典顺序进行比较,并且 '9' 确实是最大值。

What you are looking for is something like: max(int(k) for k in MyCount)你正在寻找的是这样的: 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.实际上,您在此处比较了字符“1”和“9”。 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.您将 max 用于字符串值。 You must convert them to int.您必须将它们转换为 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))

如果有人最终在这里寻找如何按值而不是键排序

max(MyCount, key=MyCount.get)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM