首页 > 解决方案 > 如何仅访问字典中的特定键?

问题描述

我正在解决 Hackerrank 上的一个问题,我正在使用字典:

dic = {'1':type1, '2':type2, '3':type3, '4',type4, '5',type5}

在我的问题中,我需要返回具有最大值的键(类型变量是每种类型的计数)。就像如果值为type43(type4 计数为 3)那么我需要返回 key '4'。我怎么做?

我尝试使用keys()items()函数,但它们返回列表而不是特定元素。

type1 = 0
type2 = 0
type3 = 0
type4 = 0
type5 = 0
maxim = 0
for i in arr:
    if i == 1:
        type1+=1
    elif i == 2:
        type2+=1
    elif i == 3:
        type3+=1
    elif i == 4:
        type4+=1
    else:
        type5+=1
dic = {'1':type1, '2':type2, '3':type3, '4':type4, '5':type5}
for j in range(1,len(dic)):
    if dic[str(j)]>maxim:
        maxim = dic[str(j)]
return maxim

我的输出结果是 3,这是其中一个类型变量持有的最大计数,但我需要的是让它将键返回到相应的值(这里值是 3,键是 4)。

标签: python-3.xdictionary

解决方案


您清理的代码将导致:

arr = [1,2,3,2,3,4,5,3,4,21,1,2,3,2,3,4,5,6,5,4,3,2,3,4,1,1,1,2]
dic = {}
for i in arr:
    dic.setdefault(i,0)    # set count of 0 if not existent
    dic[i] +=1             # increase count

# use the builtin max function to get the item with the highest count
m = max(dic.items(), key = lambda x:x[1])

print(m)  # (3,7)

dict.setdefault

使用 acollections.Counter会加快速度,它是一个专门计算事物的字典:

from collections import Counter
arr = [1,2,3,2,3,4,5,3,4,21,1,2,3,2,3,4,5,6,5,4,3,2,3,4,1,1,1,2]

# feed the array into Counter (which is a specialized counting dictionary)
c = Counter( arr )
print(c.most_common())

key, occ = c.most_common()[0]
print( key,"occured",occ,"times")

输出:

# counter.most_common() - i.e. 3 occured 7 time, 2 occured 6 times etc. it is sorted
[(3, 7), (2, 6), (1, 5), (4, 5), (5, 3), (6, 1), (21, 1)]

3 occured 7 times

推荐阅读