Python帮助:从csv文件创建{str:list of str}的字典 [英] Python Help: Creating a dict of {str:list of str} from csv file
问题描述
我必须以以下格式创建表格: {str:list of str}
I have to create a table in the format: {str: list of str}
.csv文件使用以下代码,我得到:
Opening a .csv file using the following code, I get:
import csv
cr = csv.reader(open("name.csv","r"))
for row in cr:
print(row)
b $ b
输出:
output:
['key1', 'key2', 'key3']
['value1', 'value2', 'value3']
['value4', 'value5', 'value6']
我基本上需要将其结构化为
I essentially need to structure this into the format
{'key1': ['value1', 'value4'], 'key2': ['value2', 'value5'], 'key3': ['value3', 'value6']}
我被卡住了;我只是想不出一种方法来为它工作任何数量的键和值
I'm stuck; I just can't think of a way to do this for it to work for any number of keys and values
推荐答案
使用 zip()
将行转成列,然后将它们转换为字典键和值:
Use zip()
to turn rows into columns, then make those into dictionary keys and values:
import csv
with open("name.csv", newline='') as infh:
cr = csv.reader(infh)
columns = {r[0]: list(r[1:]) for r in zip(*cr)}
最后一行的快速演示:
>>> cr = [
... ['key1', 'key2', 'key3'],
... ['value1', 'value2', 'value3'],
... ['value4', 'value5', 'value6'],
... ]
>>> {r[0]: list(r[1:]) for r in zip(*cr)}
{'key3': ['value3', 'value6'], 'key2': ['value2', 'value5'], 'key1': ['value1', 'value4']}
cr
代表 csv.reader()
对象。
zip(* iterable)
获取迭代中的所有元素,并将其转换为矩阵;列成为行,因为每个嵌套值与位于相同位置的其他行的值配对。
zip(*iterable)
takes all elements in an iterable and transforms it like a matrix; columns become rows as each nested value is paired up with values from the other rows at the same position:
>>> zip(*[[1, 2, 3], [4, 5, 6]])
[(1, 4), (2, 5), (3, 6)]
和字符解析 {key_expression:value_expression for iterates}
一个字典,其中在上面的代码中一列中的每个第一个元素成为键,其余的形成值。
and the dict comprehension {key_expression: value_expression for targets in iterable}
produces a dictionary, where in the above code each first element in a column becomes the key, and the rest forms the value.
这篇关于Python帮助:从csv文件创建{str:list of str}的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!