Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
user1452759 Avatar asked Nov 12 '14 07:11

user1452759


People also ask

How do you create a dictionary from a list of keys and values?

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.

Can dictionary values be a list Python?

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.

How do you write a dictionary to a .CSV in Python?

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().


2 Answers

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'}
like image 131
user1452759 Avatar answered Oct 11 '22 20:10

user1452759


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

like image 37
Nilesh Avatar answered Oct 11 '22 20:10

Nilesh