简体   繁体   English

Python从文件中检索带有列表的字典

[英]Python Retrieve Dictionary with List from File

Hello i have a dictionary file named output.csv created by a dictionary with key:List and has the following form 您好我有一个名为output.csv的字典文件,由字典创建,其中包含键:List并具有以下形式

A,['TEST1']

B,['TEST2']

C,"['TEST1', 'TEST3']"

D,['TEST2']

E,"['TEST1', 'TEST2']"

Now i try to access it from a different python script by using the following 现在我尝试使用以下内容从不同的python脚本访问它

reader = csv.reader(open('output.csv', 'r'))
d = {}
for row in reader:
   k, v = row
   d[k] = v

Although i get this error 虽然我得到这个错误

line 9, in <module>
    k, v = row
ValueError: need more than 0 values to unpack

What could be the problem? 可能是什么问题呢?

If you want to create the dictionary back you can do: 如果要创建字典,可以执行以下操作:

import csv

reader = csv.reader(open('output.csv'))
d = {}
for row in reader:
  if row:
    k = row[0]
    v = row[1]
    d[k] = v
print d

Output: 输出:

{'A': "['TEST1']", 'B': "['TEST1' 'TEST3']", 'C': "['TEST2']",
 'D': "['TEST1' 'TEST2']", 'E': "['TEST2']"}

EDIT (a little explaining): This works because the delimiter value for csv.reader() defaults to , so it returns a list with two elements in your case. 编辑(一点解释):这是有效的,因为csv.reader()的分隔符值默认为,所以它返回一个包含两个元素的列表。 You can of course set it to something else if you want, I just assumed you want to split it by commas. 如果你愿意,你当然可以把它设置成别的东西,我只是假设你想用逗号分割它。 To set it to something else you can do: 要将其设置为其他可以执行的操作:

csv.reader(open('output.csv'), delimiter=']')

You have empty lines and possibly some lines with spaces, which get csv-unpacked as no values or one value, respectively. 你有空行,可能还有一些带空格的行,它们分别将csv-unpacked作为无值或一个值。 Add a line to ignore those: 添加一行来忽略这些:

for row in reader:
    if len(row)!=2: continue
    k, v = row

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

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