如何使用Counter在字典中打印出带有count的值

时间:2019-09-05 11:02:55

标签: python dictionary

我的代码在

下方
def tuptodi(tup, dictio): 
    for a, b in tup: 
        dictio.setdefault(a, []).append(b) 
    return dictio
tups = [('key1', 'value1'), ('key2', 'value1'),('key3', 'value3'),('key1', 'value1'),('key1', 'value2')]
dictionary = {} 
print (tuptodi(tups, dictionary)) 

我的出场

{'key1': ['value1', 'value1', 'value2'], 'key2': ['value1'], 'key3': ['value3']}

我想要的出场

{'key1':{'value1':2},
{'key2':{'value1':1},
{'key3':{'value3':1}

如何通过from collections import Counter

实现此目标

2 个答案:

答案 0 :(得分:2)

在字典理解中使用Counter

from collections import Counter

data = {'key1': ['value1', 'value1', 'value2'], 'key2': ['value1'], 'key3': ['value3']}
out  = {key: Counter(sublist) for key, sublist in data.items()}

print(out)
# {'key1': Counter({'value1': 2, 'value2': 1}), 
#  'key2': Counter({'value1': 1}), 
#  'key3': Counter({'value3': 1})}

答案 1 :(得分:2)

使用collections.Counterdefaultdict

from collections import Counter, defaultdict

tups = [('key1', 'value1'), ('key2', 'value1'),('key3', 'value3'),('key1', 'value1'),('key1', 'value2')]
cnt = defaultdict(Counter)

for i,j in tups:
    cnt[i].update([j])

cnt

输出:

defaultdict(collections.Counter,
            {'key1': Counter({'value1': 2, 'value2': 1}),
             'key2': Counter({'value1': 1}),
             'key3': Counter({'value3': 1})})