python在dict中运行值的计数

时间:2015-03-26 03:16:37

标签: python dictionary counter

我有这样的字典

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]}

3 个答案:

答案 0 :(得分:6)

要强制执行订单(dict本身没有订单),假设您按键上的已排序顺序。然后你可以做 - 假设值是可以清除的,如你的例子......:

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

答案 1 :(得分:6)

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

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来跟踪输入字典中名称的出现。希望这可以帮助。也许不是最优雅的代码,但它的工作原理。

答案 2 :(得分:4)

不使用任何模块,这是我提出的代码。也许不是那么短暂,但我害怕模块。

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]}