May 24, 2020

csv file to dict

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:
            _dict[k] = type_per_key[k](v) if k in type_per_key else v
    return array_of_dicts

 

0 0 votes
Article Rating

Share the knowledge on

Do you like my content? You can support me at
Buy Me A Coffee
Subscribe
Notify of
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

Great content! Keep up the good work!

Admin
3 years ago
Reply to  Samtrygg

Thanks