Home > Software design >  I want to create a nested dictionary from a csv file with headers as keys
I want to create a nested dictionary from a csv file with headers as keys

Time:11-29

This is my csv file:

Player Name,2022 Cap Number,Rating,Position
Poona Ford,"10,075,000",74,DT
Tyler Lockett,"10,050,000",90,WR
D.K. Metcalf,"8,838,827",89,WR
Gabe Jackson,"7,237,778",79,G
Uchenna Nwosu,"6,295,000",79,LB
Quandre Diggs,"5,800,000",85,FS

I want my output to be:

{'Poona Ford': {'2022 Cap Number': '"10075000"', 'Rating': '74', 'Position': 'DT'}, 'Tyler Lockett': {'2022 Cap Number': '"10050000"', 'Rating': '90', 'Position': 'WR'}, 'D.K. Metcalf': {'2022 Cap Number': '"8838827"', 'Rating': '89', 'Position': 'WR'}, 'Gabe Jackson': {'2022 Cap Number': '"7237778"', 'Rating': '79', 'Position': 'G'}, 'Uchenna Nwosu': {'2022 Cap Number': '"6295000"', 'Rating': '79', 'Position': 'LB'}, 'Quandre Diggs': {'2022 Cap Number': '"5800000"', 'Rating': '85', 'Position': 'FS'}

I've been able to produce this but the names are the only keys. I need the other header names to be keys within each name. '2002 Cap Number' , 'Rating', and 'Postion' need to be keys within Player Name.

csv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '"10075000"', '74', 'DT'], ['Tyler Lockett', '"10050000"', '90', 'WR'], ['D.K. Metcalf', '"8838827"', '89', 'WR'], ['Gabe Jackson', '"7237778"', '79', 'G'], ['Uchenna Nwosu', '"6295000"', '79', 'LB'], ['Quandre Diggs', '"5800000"', '85', 'FS']

(_, *header), *data = csv_list
csv_dict = {}
for row in data:
    key, *values = row
    csv_dict[key] = {key: value for key, value in zip(header, values)}

print(csv_dict)

I tried this but only the names are keys. The rest of the headers and data are all values.

CodePudding user response:

Try this:

csv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '"10075000"', '74', 'DT'], ['Tyler Lockett', '"10050000"', '90', 'WR'], ['D.K. Metcalf', '"8838827"', '89', 'WR'], ['Gabe Jackson', '"7237778"', '79', 'G'], ['Uchenna Nwosu', '"6295000"', '79', 'LB'], ['Quandre Diggs', '"5800000"', '85', 'FS']]

csv_dict = {}
for i,*j in csv_list[1:]:
    csv_dict[i] = dict(zip(csv_list[0][1:], j))
  • Related