列为字典中的值,获取最长列表的键 [英] List as value in dictionary, get key of longest list
本文介绍了列为字典中的值,获取最长列表的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给这样的字典
testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59]}
如何获取最长列表的密钥?在这种情况下,它将是32
.
How do I get the key of the longest list? In this case it would be 32
.
推荐答案
使用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]
这篇关于列为字典中的值,获取最长列表的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文