简体   繁体   English

在字典中列出值,获取最长列表的键

[英]List as value in dictionary, get key of longest list

Give a dictionary like this 给这样的字典

testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59]}

How do I get the key of the longest list? 我如何获得最长列表的密钥? In this case it would be 32 . 在这种情况下,它将是32

Use max : 使用max

>>> max(testDict, key=lambda x:len(testDict[x]))
32

If multiple keys contain the longest list: 如果多个键包含最长列表:

I want to get multiple keys then. 我想获得多个密钥。

>>> testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59], 10: [1, 2, 3, 4]}
>>> mx = max(len(x) for x in testDict.itervalues())
>>> [k for k, v in testDict.iteritems() if len(v)==mx]
[32, 10]

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

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