在字典中找出最常见的值并分配给键

时间:2019-06-18 16:43:36

标签: python python-3.x

我有一本字典,其中以字符串为键,还以字符串为值。第一, 我想在我的词典中找到最频繁的val。其次,我想为键分配最频繁的值

input_dict = {
    'A': [1963], 'B': [1963,1964] 
    'C': [1966], 'D': [1964,1965] 'E': [1965,1967]
    'F': [1968,1969] 'G': [1969], 'H': [1971,1966]
    'I': [1967], 'J': [1967], 'K': [1968,1969]
    'L': [1969] ,'M': [1969],
    'N': [1970,1971]}

现在,如果我们计算此字典中最频繁的val,则为:

year    No. of times occurrence

1969    5 times
1967    3 times
1963    2 times
1964    2 times
1965    2 times
1966    2 times
1968    2 times
1971    2 times
1970    1 times

如果该键中存在该值,我只想给该键分配一个最频繁的val。如果出现次数相同,则应该是其中任何一个

预期输出:

{'A': [1963], 'B': [1963], 'C': [1966], 'D': [1964], 'E': [1967],'F': [1969] 'G': [1969], 'H': [1971],'I': [1967], 'J': [1967], 'K': [1969],'L':[1969],'M': [1969],'N': [1971]}

2 个答案:

答案 0 :(得分:1)

您必须使用收藏夹模块

input_dict = {
    'A': [1963], 'B': [1963,1964] ,
    'C': [1966], 'D': [1964,1965] , 'E': [1965,1967],
    'F': [1968,1969] , 'G': [1969], 'H': [1971,1966],
    'I': [1967], 'J': [1967], 'K': [1968,1969],
    'L': [1969] ,'M': [1969],
    'N': [1970,1971]}
l = []
for x in input_dict.values():
    for y in x: #because your values are lists
        l.append(y)
import collections
counter = collections.Counter(l)
#counter calculates the frequencies for you
m = []
for x,y  in dict(counter).items():
    m.append(counter.most_common(1)[0][0])
    del counter[counter.most_common(1)[0][0]]

m是您的频率列表 现在用于eack密钥,如果不存在m [1],则检查是否存在m [0]的值,依此类推

如果您在评论中遇到问题,请告诉我

答案 1 :(得分:0)

您可以执行以下操作。我不确定您要如何分配密钥,因为有些密钥具有保存的次数,因此请您自行承担。

Online Compiler Version

input_dict = {
    'A': [1963], 'B': [1963,1964], 
    'C': [1966], 'D': [1964,1965], 'E': [1965,1967],
    'F': [1968,1969], 'G': [1969], 'H': [1971,1966],
    'I': [1967], 'J': [1967], 'K': [1968,1969],
    'L': [1969] ,'M': [1969],
    'N': [1970,1971]}


popularity_dict = {}
for key in input_dict:
    items = input_dict[key]
    for item in items:
        try:
            popularity_dict[str(item)] = popularity_dict[str(item)] + 1
        except:
            popularity_dict[str(item)] = 1
print(popularity_dict)

#Go through each key and resassing value if needed
for key in input_dict:
    if len(input_dict[key]) > 1:
        print('Bad finding most recent year')
        mostPopYear = 0
        for year in input_dict[key]:
            print(year)
            pop = popularity_dict[str(year)]
            if pop > mostPopYear:
                mostPopYear = pop
                mostPop = year

        input_dict[key] = [mostPop]

print(input_dict)