简体   繁体   English

Python - 从 CSV 读取列表字典

[英]Python - Read Dictionary of Lists from CSV

I'm trying to read a dictionary of List from a CSV file.我正在尝试从 CSV 文件中读取 List 字典。 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:这些数据结构使用以下代码存储在 CSV 文件中:

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

I read the CSV in this way:我以这种方式阅读CSV:

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?如何从我的 CSV 文件中正确检索完整的列表字典?

You wrote the repr() output of the nested list here:您在此处编写了嵌套列表的repr()输出:

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

here val is [u'x', 'y', 'z'] ;这里val[u'x', 'y', 'z'] ; to store that in one column the csv file simply writes the result of repr(val) .要将其存储在一列中, csv文件只需写入repr(val)的结果。

You can decode that string to a Python object again with the ast.literal_eval() function :您可以使用ast.literal_eval()函数将该字符串再次解码为 Python 对象:

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 . ast.literal_eval()将输入解释为 Python 表达式,但仅限于字面量,Python 语法定义了字典、列表、元组、集合和字符串、数字、布尔值和None

You need to de-serialize the value, you can use json module:您需要反序列化该值,您可以使用json模块:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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