简体   繁体   中英

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)

I'm afraid that csv.reader(f) does not return what you are expecting it to return. I don't know exactly how your .csv file looks like, but I doubt that it directly returns the two values that you are trying to put into the dictionary.

Assuming that the first 3 lines of your .csv look something like this:

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

a better way to get the .cvs and iterate over each line might be:

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

From csv documentation ...

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

I guess it's pretty self explanatory...

I think each row of that list is a dictionary you're expecting. So your dict processing code should go inside a iteration which will iterate over the fat list returned by the csv.reader

It is saying that csv.reader(f) is yielding only one thing that you are trying to treat as two things (key and val).

Presuming that you are using the standard csv module, then you are getting a list of only one item. If you expect the input to have two items, then perhaps you need to specificity a different delimiter. For example if your input has semi colons instead of commas:

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

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