Python Help: Creating a dict of {str:list of str} from csv file

烈酒焚心 提交于 2019-12-22 18:19:35

问题


I have to create a table in the format: {str: list of str}

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)

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


回答1:


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)}

A quick demo of the last line:

>>> 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']}

where cr stands in for the csv.reader() object.

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)]

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.



来源:https://stackoverflow.com/questions/20292600/python-help-creating-a-dict-of-strlist-of-str-from-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!