I have a csv file, test.csv
, as shown:
1,2,3
a,b,c
d,e,f
I want the above to look like a dictionary as shown:
{"1":"a", "2":"b", "3":"c"}
{"1":"d", "2":"e", "3":"f"}
where the header 1,2,3
are the keys and the rows are values.
I don't quite understand how to get this done using csv.DictReader. The above sample is just that, a sample. The actual data that I'm working with has many columns, and hence, I cannot access each row by using its index and manually putting them into a dictionary.
To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.
It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.
In Python to convert a dictionary to CSV use the dictwriter() method. This method is used to insert data into the CSV file. In Python, the CSV module stores the dictwriter() method. It creates an object and works like the dictwriter().
Answering my own question. After trying for sometime I just now played around with it a bit more and added the for loop.
with open("test.csv") as f:
records = csv.DictReader(f)
for row in records:
print row
This gives my desired output of
{'1': 'a', '3': 'c', '2': 'b'}
{'1': 'd', '3': 'f', '2': 'e'}
By default first line will take as filedname in csv.DictReader
you can try
>>> a = open('/tmp/test.csv')
>>> a = csv.DictReader(open('/tmp/test.csv'), delimiter=',')
>>> [x for x in a]
[{'1': 'a', '3': 'c', '2': 'b'}, {'1': 'd', '3': 'f', '2': 'e'}]
This might be what your want
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With