csv file to dict

 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
def csv_to_dict(path, allowed_keys=None):
    """
    Reads csv file and returns dict with keys specified in allowed_keys
    parameter; if allowed_keys is Falsy, it will include all columns.

    path - string, path to file
    allowed_keys - array of strings, columns that you want in the result JSON

    return - dict
    """

    rows_json = []
    try:
        with open(path, 'r') as csv_file:
            csv_content = csv_file.readlines()
        keys = {i: k for i, k in enumerate(csv_content[0].split(','))}
        if not allowed_keys:
            allowed_keys = set(keys.values())
        for row in csv_content[1:]:
            row = row.split(',')
            rows_json.append({keys[i]: (k if k != 'NaN' else None) for i, k in enumerate(row) if keys[i] in allowed_keys})
    except Exception:
        import traceback
        traceback.print_exc()

    return rows_json


def convert_dict_values(array_of_dicts, type_per_key):
    """Convert type of values in dictionary

    - array_of_dicts, i.e. [{'pressure': '2.4', 'wheels': '0', 'name': 'Audi'}, ...]
    - type_per_key, i.e. {'pressure': float, 'wheels': int}

    return: [{'pressure': 2.4, 'wheels': 0, 'name': 'Audi'}, ...]
    """
    for _dict in array_of_dicts:
        for k, v in _dict:
            i_dict[k] = type_per_key[k](v) if k in type_per_key else v
    return array_of_dicts