繁体   English   中英

解包的值太多(预期为 2)

[英]too many values to unpack (expected 2)

def read_dict(file_name):
    f=open(file_name,'r')
    dict_rap={}
    for key, val in csv.reader(f):
        dict_rap[key]=str(val)
    f.close()
    return(dict_rap)
test_dict = {'wassup':['Hi','Hello'],'get up through':['to leave','to exit'],
             'its on with you':['good bye','have a nice day'],'bet':['ok','alright'],'ight':['ok','yes'],
              'whip':['car','vechile'],'lit':['fun','festive'],'guap':['money','currency'],'finesse':['to get desired results by anymeans','to trick someone'],
             'jugg':['how you makemoney','modern term for hustle'],'1111':['www'] }
Traceback (most recent call last):
     File "C:\Users\C2C\Desktop\rosetta_stone.py", line 97, in 
      reformed_dict = read_dict(file_name)#,test_dict)
      File "C:\Users\C2C\Desktop\rosetta_stone.py", line 63, in read_dict
       for key, val in csv.reader(f):
      ValueError: too many values to unpack (expected 2)

恐怕csv.reader(f)不会返回您期望它返回的内容。 我不知道你的 .csv 文件到底是什么样子,但我怀疑它是否直接返回了你试图放入字典的两个值。

假设您的 .csv 的前 3 行如下所示:

wassup,hi,hello
get up through,to leave,to exit
its on you,good bye,have a nice day

获取 .cvs 并迭代每一行的更好方法可能是:

...
my_csv = csv.reader(f)
for row in my_csv:
    # row is a list with all the values you have in one line in the .csv
    if len(row) > 1:
        key = row[0] # for the 1st line the value is the string: 'wassup'
        values = row[1:] # here for the first line you get the list: ['hi', 'hello']
        # ... and so on

csv文档...

In [2]: csv.reader??
Docstring:
csv_reader = reader(iterable [, dialect='excel']
                        [optional keyword args])
    for row in csv_reader:
        process(row)
......
......
The returned object is an iterator.  Each iteration returns a row

我想这是不言自明的......

我认为该列表的每一行都是您期望的字典。 所以你的dict处理代码应该进入一个迭代,它将迭代csv.reader返回的胖列表

它是说 csv.reader(f) 只产生一件事,您试图将其视为两件事(key 和 val)。

假设您使用的是标准 csv 模块,那么您将获得仅包含一项的列表。 如果您希望输入有两个项目,那么您可能需要指定不同的分隔符。 例如,如果您的输入有分号而不是逗号:

csv.reader(f, delimiter=";")

暂无
暂无

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

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