List as value in dictionary, get key of longest list

后端 未结 1 660
长发绾君心
长发绾君心 2021-01-13 03:50

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

1条回答
  •  别那么骄傲
    2021-01-13 04:43

    Use 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]
    

    0 讨论(0)
提交回复
热议问题