Jan-14-2019, 12:08 AM
but the second csv record with name john will overwrite the first.
result:
{'john': {'email': 'hello.com', 'date': '12/08/18', 'phone': '123456'}}
but can be saved with json.dump
code again with json dump and reread json:
import csv import os # I need following for my virtual environment, you can remove if # running python from same directory as csv file. os.chdir(os.path.abspath(os.path.dirname(__file__))) result = [] plain_dict = {} # To get flat normal dict, can just use dict(ordered_dict) # but to get name as key: with open("student.csv", "r") as csv_ledger: name = None reader = csv.DictReader(csv_ledger) for row in csv.DictReader(csv_ledger, skipinitialspace=True): for k, v in row.items(): if k == 'name': name = v plain_dict[name] = {} else: plain_dict[name][k] = v print(plain_dict)and since there are two csv rows with sane name, second overwrites first.
result:
{'john': {'email': 'hello.com', 'date': '12/08/18', 'phone': '123456'}}
but can be saved with json.dump
code again with json dump and reread json:
import csv import json import os # I need following for my virtual environment, you can remove if # running python from same directory as csv file. os.chdir(os.path.abspath(os.path.dirname(__file__))) result = [] plain_dict = {} # To get flat normal dict, can just use dict(ordered_dict) # but to get name as key: with open("student.csv", "r") as csv_ledger: name = None reader = csv.DictReader(csv_ledger) for row in csv.DictReader(csv_ledger, skipinitialspace=True): for k, v in row.items(): if k == 'name': name = v plain_dict[name] = {} else: plain_dict[name][k] = v print(f'plain_dict: {plain_dict}') with open('student.json', 'w') as jp: json.dump(plain_dict, jp) # reload json to make sure ok with open('student.json') as jp: new_dict = json.load(jp) print(f'new_dict: {new_dict}')output:
Output:plain_dict: {'john': {'email': 'hello.com', 'date': '12/08/18', 'phone': '123456'}}
new_dict: {'john': {'email': 'hello.com', 'date': '12/08/18', 'phone': '123456'}