python 运行 字典中的值计数

python running count of values in dict

我有这样的字典

d = {1:'Bob', 2:'Joe', 3:'Bob', 4:'Bill', 5:'Bill'}

我想记录每个名称作为字典值出现的次数。所以,输出应该是这样的:

d = {1:['Bob', 1], 2:['Joe',1], 3:['Bob', 2], 4:['Bill',1] , 5:['Bill',2]}

要强加一个顺序(dict 本身没有),假设您要按 sorted 顺序排列键。然后你可以做 - 假设值是可散列的,就像你的例子......:

import collections

def enriched_by_count(somedict):
    countsofar = collections.defaultdict(int)
    result = {}
    for k in sorted(somedict):
        v = somedict[k]
        countsofar[v] += 1
        result[k] = [v, countsofar[v]]
    return result

一种计算所需值的方法如下所示:

from collections import Counter


d = {1:'Bob',2:'Joe',3:'Bob', 4:'Bill', 5:'Bill'}


c = Counter()
new_d = {}

for k in sorted(d.keys()):
    name = d[k]
    c[name] += 1;  
    new_d[k] = [name, c[name]]

print(new_d)  
# {1: ['Bob', 1], 2: ['Joe', 1], 3: ['Bob', 2], 4: ['Bill', 1], 5: ['Bill', 2]}

这里我使用 Counter 来跟踪输入字典中出现的名称。希望这可以帮助。也许不是最优雅的代码,但它确实有效。

在不使用任何模块的情况下,这是我想出的代码。也许没那么短,但我害怕模块。

def new_dict(d):
    check = [] #List for checking against
    new_dict = {} #The new dictionary to be returned
    for i in sorted(d.keys()): #Loop through all the dictionary items
        val = d[i] #Store the dictionary item value in a variable just for clarity
        check.append(val) #Add the current item to the array
        new_dict[i] = [d[i], check.count(val)] #See how many of the items there are in the array

    return new_dict

这样使用:

d = {1:'Bob', 2:'Joe', 3:'Bob', 4:'Bill', 5:'Bill'}
d =  new_dict(d)
print d

输出:

{1: ['Bob', 1], 2: ['Joe', 1], 3: ['Bob', 2], 4: ['Bill', 1], 5: ['Bill', 2]}