简体   繁体   中英

Python - Read Dictionary of Lists from CSV

I'm trying to read a dictionary of List from a CSV file. I'm trying to access to data-structure like:

dbfree = {u'keyname': [u'x', 'y', 'z']}

These data structures are stored in a CSV file with this code:

for key, val in dbfree.items():
     w.writerow([key, val])

I read the CSV in this way:

dbproj = {}
for key, val in unicodecsv.reader(open(filename)):
    dbproj[key] = val

But the output is this:

{u'key name': u"[u'x', 'y', 'z']"

How can I correctly retrieve the full dictionary of lists from my CSV file?

You wrote the repr() output of the nested list here:

for key, val in dbfree.items():
    w.writerow([key, val])

here val is [u'x', 'y', 'z'] ; to store that in one column the csv file simply writes the result of repr(val) .

You can decode that string to a Python object again with the ast.literal_eval() function :

import ast

dbproj = {}
for key, val in unicodecsv.reader(open(filename)):
    dbproj[key] = ast.literal_eval(val)

ast.literal_eval() interprets the input as a Python expression, but limited to literals , Python syntax that defines objects such as dictionaries, lists, tuples, sets and strings, numbers, booleans and None .

You need to de-serialize the value, you can use json module:

import json

 for key, val in dbfree.items():
      w.writerow([key, json.dumps(val)])

for reading:

dbproj = {}
for key, val in unicodecsv.reader(open(filename)):
    dbproj[key] = json.loads(val)

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