Skip to content
Advertisement

Python split function. Too many values to unpack error

I have a python function that must read data from file and split it into two key and value, and then store it in dictionary. Example: file:

JavaScript

I use the split function for it, but when there is really a lot of data it raises value error

JavaScript

What can I do about this ?

This is the exact code that fails

JavaScript

Advertisement

Answer

You are trying to unwrap the split list in to these two variables.

JavaScript

What if there is no space or two or more spaces? Where will the rest of the words go?

JavaScript

You can actually check the length before assigning

JavaScript

With the input file,

JavaScript

This program produces,

JavaScript

Following @abarnert’s comment, you can use partition function like this

JavaScript

If there are more than one spaces/no space, then count will hold rest of the string or empty string, respectively.

If you are using Python 3.x, you can do something like this

JavaScript

First two values will be assigned in first and second respectively and the rest of the list will be assigned to rest, in Python 3.x

Advertisement