-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfrom_csv_to_dictionary.py
57 lines (41 loc) · 1.35 KB
/
from_csv_to_dictionary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 13:34:41 2018
@author: booort, ruhugu
"""
import csv
# Read CSV file
def csv2dict(filename, delimiter=";"):
"""Reads a 2-column csv file into a dict.
The value in the first column is used as dictionary key. The value
of the dict entry is a list with the value of the second column.
If several rows have the value in the first column, their
second column values are stored in the same list.
Parameters
----------
filename : str
Name of the file to be read.
delimiter : str
Delimiter used in the csv file.
"""
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter=delimiter)
dictionary = {}
for entry in reader:
key = entry[0]
value = entry[1]
# If the key is already in the dict, append the value
# to the list
if key in dictionary:
dictionary[key].append(value)
# In other case, create a new dict entry
else:
dictionary[key] = [value, ]
return dictionary
# Test the function
dictionary = csv2dict("Definitiva.csv", delimiter=";")
for key in dictionary:
print("{0}:".format(key))
print(dictionary[key])
print("===============================")