如何计算与键关联的值的数量

时间:2012-07-12 09:35:03

标签: python dictionary find key

鉴于以下字典,我想找出哪个键具有最多值。如果我有一个更长的字典,并想知道哪个键以编程方式具有最多的值(没有目视检查),我将如何去做呢?我能想到的唯一方法如下:

dic = {'attacks': ['kick','puch','slap','elbow'], \
  'defense': ['block','parry','dodge']}

dic = {'attack':['kick','puch','slap','elbow'],'defense':['block','parry','dodge']}

key_values_list = []
for key in dic:
    key_name = ''
    num = 0 
    for item in dic[key]:
        num +=1
    key_values_list.append((key,num))

for  k,v in key_values_list:
    print k,v

2 个答案:

答案 0 :(得分:5)

>>> dic = {'attacks': ['kick','puch','slap','elbow'], 'defense': ['block','parry','dodge']}
>>> max(dic, key=lambda k: len(dic[k]))
'attacks'

答案 1 :(得分:5)

以下代码将计算标记为攻击的密钥的实例:

>>> max(((k, len(v)) for k, v in dic.items()), key=lambda x: x[1])
('attacks', 4)
>>>