mon*_*dle 0 python csv dictionary
假设我有一个csv文件,并且想要一个每个值有多个键的字典.
示例csv:
col1,col2,col2,col4,col5
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
a3,b3,c3,d3,e3
Run Code Online (Sandbox Code Playgroud)
您将如何创建字典,以便专门提取列1,2,3作为键并使用col5作为值.
输出:
{(a1,b1,c1):e1 , (a2,b2,c2):e2 , (a3,b3,c3):e3 }
Run Code Online (Sandbox Code Playgroud)
有没有方法可以做到这一点?
你可以使用dict理解:
import csv
with open(filename, 'rb') as infh:
reader = csv.reader(infh)
next(reader) # skip the header row
result = {tuple(row[:3]): row[4] for row in reader}
Run Code Online (Sandbox Code Playgroud)
字典的键必须是不可变的; 的csv.reader()产生列表,以便从我使用的切片和第3列产生的元组tuple()的功能.
演示:
>>> import csv
>>> sample = '''\
... col1,col2,col2,col4,col5
... a1,b1,c1,d1,e1
... a2,b2,c2,d2,e2
... a3,b3,c3,d3,e3
... '''
>>> reader = csv.reader(sample.splitlines())
>>> next(reader)
['col1', 'col2', 'col2', 'col4', 'col5']
>>> {tuple(row[:3]): row[4] for row in reader}
{('a3', 'b3', 'c3'): 'e3', ('a2', 'b2', 'c2'): 'e2', ('a1', 'b1', 'c1'): 'e1'}
Run Code Online (Sandbox Code Playgroud)