1

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

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

dic = {'攻击':['踢','puch','slap','肘部'],'防御':['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
4

2 回答 2

5
>>> dic = {'attacks': ['kick','puch','slap','elbow'], 'defense': ['block','parry','dodge']}
>>> max(dic, key=lambda k: len(dic[k]))
'attacks'
于 2012-07-12T09:36:32.453 回答
5

以下代码将计算关键标记攻击的实例:

>>> max(((k, len(v)) for k, v in dic.items()), key=lambda x: x[1])
('attacks', 4)
>>>
于 2012-07-12T09:39:58.013 回答