Skip to main content
 首页 » 编程设计

python之如何将多个列表转换为python中的字典

2025年05月04日15youxin

['*a*', '*b*', '*c*', '*d*', '*f*','*g*'] 
['11', '22', '33', '44', '', '55'] 
['66', '77', '88', '', '99', '10'] 
['23', '24', 'sac', 'cfg', 'dfg', ''] 

需要放入字典中为:

{a : ('11','66','23'),b : ('22','77','24'),c : ('33','88','sac'),d :('44','','cfg')} 

行是从 CSV 文件中读取的:

import csv 
csvFile = csv.reader(open("sach.csv", "rb")) 
for row in csvFile: 
    print row 

上面显示的代码, 行的输出如上所示,其中包含许多列表。 请帮我把它变成如上所示的字典格式。

请您参考如下方法:

压缩行:

with open("sach.csv", "rb") as csv_infile: 
    reader = csv.reader(csv_infile) 
    yourdict = {r[0].replace('*', ''): r[1:] for r in zip(*reader)} 

zip() function通过传入带有 * 参数的 reader 对象,为您进行配对 Python 将遍历 CSV 行并将每一行作为单独的参数传递给 zip ()。