问题
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