首页 > 解决方案 > 如何计算键中值的出现次数?

问题描述

我已经检查了解决方案,字典:如何计算列表中值的频率 - Python3、stackoverflow 以及 google 中的其他选项。而不是从键中获取出现次数。我从单词中收到了字符的数量,但实际上没有收到单词的数量。

import csv
from collections import defaultdict

content = "Note.csv"
collector = {}
with open(content, 'r') as file:
    genres = csv.DictReader(file, skipinitialspace=True)
    for row in genres:
        collector = {"Genre": f'{row["others"]}',
                     "Title": f'{row["title"]}'}
        print(collector)
        colors = ['r','g']
        for k, v in collector.items():
            D = defaultdict(list)
            for i, item in enumerate(v):
                D[item].append(i)
            D = {k: v for k, v in D.items()}
            print(k, D)

Note.csv 包含以下内容:

title, author, year, others, note
Everything,Nobody,2222,Fiction,This is just something of everything!
Nothing,Everybody,1111,Romance,This is nothing of anything!
Pokemon,Pikachu,1999,Fiction,Once upon time.

最终结果实际上应该是这样的。1:浪漫;2:小说

根据结果​​,我希望能够创建一个饼图。

与往常一样,非常感谢您提供有用的意见和回答!

此致,

标签: python-3.xdictionary

解决方案


如果您只是计算每种类型的数量,您可以使用 a Counter

from collections import Counter

with open(content, 'r') as file:
    genres = csv.DictReader(file, skipinitialspace=True)
    c = Counter(row["others"] for row in genres)

print(c)
# Counter({'Fiction': 2, 'Romance': 1})

推荐阅读