user17143278
user17143278

Reputation:

How to make dictionary key-value with CSV file?

I have CSV file look like this, have 8 columns. I want to make dictionary key with department, and value with number of departments. Check the cvs file image :

enter image description here

example of print out

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

so I wrote the code like this way, but it doesn't work well.

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)

Upvotes: 0

Views: 285

Answers (1)

xBurnsed
xBurnsed

Reputation: 452

You could use 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())

Example output:

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

Upvotes: 1

Related Questions