首页 > 解决方案 > 如何打印最大长度的字典键?

问题描述

x = {'0': 'test1', 
     '1': 'test2', 
     '98hbu98hg7': 'test4', 
     '21292392392494223423432423': 'test3'}

print(max(x.keys()))

打印出来:

98hbu98hg7

代替:

21292392392494223423432423

难道我做错了什么?

标签: pythonpython-3.xdictionary

解决方案


默认情况下,通过比较max返回最大的项目。意思是,使用. 并且由于您的键是字符串,因此会打印出来,因为它在字典上是最大的(因为在 之后)。<'98hbu98hg7'92

您可以使用key关键字参数指定不同的排序函数:

x = {'0': 'test1', '1': 'test2', '98hbu98hg7': 'test4', '21292392392494223423432423': 'test3'}

print(max(x.keys(), key=len))

这打印:

21292392392494223423432423

推荐阅读