gpt4 book ai didi

python csv到字典列

转载 作者:行者123 更新时间:2023-11-28 19:55:09 24 4
gpt4 key购买 nike

是否可以将 csv 文件中的数据读取到字典中,以便列的第一行是键,同一列的其余行构成作为列表的值?

例如我有一个 csv 文件

     strings, numbers, colors 
string1, 1, blue
string2, 2, red
string3, 3, green
string4, 4, yellow

使用

with open(file,'rU') as f: 
reader = csv.DictReader(f)
for row in reader:
print row

我得到

{'color': 'blue', 'string': 'string1', 'number': '1'}
{'color': 'red', 'string': 'string2', 'number': '2'}
{'color': 'green', 'string': 'string3', 'number': '3'}
{'color': 'yellow', 'string': 'string4', 'number': '4'}

或使用

 with open(file,'rU') as f: 
reader = csv.reader(f)
mydict = {rows[0]:rows[1:] for rows in reader}
print(mydict)

我得到以下字典

{'string3': ['3', 'green'], 'string4': ['4', 'yellow'], 'string2': ['2', 'red'], 'string': ['number', 'color'], 'string1': ['1', 'blue']}

但是,我想得到

{'strings': ['string1', 'string2', 'string3', 'string4'], 'numbers': [1, 2, 3,4], 'colors': ['red', 'blue', 'green', 'yellow']}

最佳答案

您需要解析第一行,创建列,然后继续处理其余行。

例如:

columns = []
with open(file,'rU') as f:
reader = csv.reader(f)
for row in reader:
if columns:
for i, value in enumerate(row):
columns[i].append(value)
else:
# first row
columns = [[value] for value in row]
# you now have a column-major 2D array of your file.
as_dict = {c[0] : c[1:] for c in columns}
print(as_dict)

输出:

{
' numbers': [' 1', ' 2', ' 3', ' 4'],
' colors ': [' blue', ' red', ' green', ' yellow'],
'strings': ['string1', 'string2', 'string3', 'string4']
}

(一些奇怪的空格,它们在您的输入"file"中。删除逗号前后的空格,或者使用 value.strip() 如果它们在您的真实输入中。)

关于python csv到字典列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com