简体   繁体   中英

Python writing a csv to a list of dictionaries with headers as keys and rows as values

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM