繁体   English   中英

我想从 csv 文件创建一个嵌套字典,其中标题作为键

[英]I want to create a nested dictionary from a csv file with headers as keys

这是我的 csv 文件:

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

我希望我的 output 是:

{'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'}

我已经能够制作这个,但名称是唯一的关键。 我需要其他 header 名称作为每个名称中的键。 '2002 Cap Number'、'Rating' 和 'Postion' 需要是 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)

我试过了,但只有名字是关键。 headers和data的rest都是值。

尝试这个:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM