【问题标题】:How to make dictionary key-value with CSV file?如何使用 CSV 文件制作字典键值?
【发布时间】:2021-12-05 09:52:25
【问题描述】:

我的 CSV 文件看起来像这样,有 8 列。我想用部门制作字典键,用部门数制作价值。 检查 cvs 文件图像:

打印示例

{'Japanese': 1,
 'physiology': 1,
 'economics': 2,
 'business': 1,
 'biology': 1,
 'software': 9,
 'smart iot': 1,
 'medical': 1,
 'big data': 2}

所以我就这样写了代码,但是效果不好。

names = ['japanese', 'psychology', 'economics', 'buiseness', 'biology', 'medical', 'software', 'smart IOT', 'big data', 'electronics', 'contents IT']
names_count = len(names)
unique_dept_names = set()
unique_dept_names = {name:[] for name in names}
with open('fake_student_records.csv', mode='r', encoding='utf-8') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        for name in names:
            unique_dept_names[name].append(row['department'])
number = {name:0 for name in names}
for name in names:
    number[name] = names_count 
    
print(number)

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    你可以使用collections

    import csv
    import collections
    departments = collections.Counter()
    with open('fake_student_records.csv') as input_file:
        next(input_file) #skip first row since its column name
        for row in csv.reader(input_file, delimiter=','):
            departments[row[2]] += 1
    print ('Number of Japanese departments: '+ str(departments['Japanese']))
    print (departments.most_common())
    

    示例输出:

    Number of Japanese departments: 3
    [('Japanese', 3), ('economics', 1), ('business', 2),...]
    

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 2021-01-12
      相关资源
      最近更新 更多