能否从csv文件中读取数据到一个字典中,使得每一列的第一行作为键(key),而该列剩余的行作为值(value)保存为列表?
例如,有一个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']}
csv.DictReader
可能不是最好的选择 - 如果你按照上面的问题并稍微尝试一下 - 你应该能得到答案。例如,你可以将row[0]
收集为键,将其他所有内容收集为值rows[1:]
。现在试试看吧。 - undefined