I was looking at the accepted answer of this:
Creating a dictionary from a CSV file
I want to create a dictionary in which the first row's different columns are keys with the corresponding next row's columns as values. This seems to do the trick, but I don't understand some parts of the code. This is it:
import csv reader = csv.DictReader(open('values.csv'))
result = {} for row in reader:
for column, value in row.items(): # consider .iteritems() for Python 2
result.setdefault(column, []).append(value)
print(f"Column: {column}")
print(f"Value: {value}") print(result)
When I run this code, I get:
Column: Date
Value: 123
Column: Foo
Value: 456
Column: Bar
Value: 789
Column: Date
Value: abc
Column: Foo
Value: def
Column: Bar
Value: ghi
{'Date': ['123', 'abc'], 'Foo': ['456', 'def'], 'Bar': ['789', 'ghi']}
for the file:
Date,Foo,Bar
123,456,789
abc,def,ghi
It does the job correctly, then, so that Date is the key with the values in the same column rows under it, but I don't understand how that works in code.
What does column, value in row.items()
do, exactly? Does it mean for every column in the row (separated by a comma), consider that a value? What does the .items()
do (I looked at the documentation, but didn't get what Returns a list containing a tuple for each key value pair meant
)?
Also, what does result.setdefault(column, []).append(value)
do? I know append adds a value, but what does the syntax .setdefault(column, [])
mean (In documentation, it means Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
, which I don't get either)?
Additionally, how did the program understand that the first row is that which I want to store the keys?
I've never done Python before, and so I apologize if this is a dumb question! I just want to make a dictionary for a database, and so this seems ideal, but I want to know what each line does. Thank you in advance!