如何仅访问词典中的特定键?

时间:2019-07-14 10:31:54

标签: python-3.x dictionary

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

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

在我的问题中,我需要返回具有最大值的键(类型变量是每种类型的计数)。 就像type4的值为3(type4计数为3)一样,我需要返回键'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)。

1 个答案:

答案 0 :(得分:1)

您清理的代码将导致:

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

使用collections.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