'error with Python progromm many values to unpack

def main(data):
    data = data.replace("\n", " ")
    data = data.lstrip("{ <% list")
    data = data.strip(' %>}').strip().strip(';')
    data = data.split(" <% list")
    dictionary = {}
    for line in data:
        values, key = line.split("=:")
        values = values.strip()
        values = values.lstrip("(")
        values = values.rstrip(")")
        values = values.split(";")
        values = list(map(lambda x: x.strip(), values))
        key = key.strip()
        dictionary[key] = values
    return dictionary
print(main("{ <% list(cema_56; ator_218 ; lara_164 ; ator_370 )=: arenar; %> <% list( reer ;ina ; lebebi_345 ) =: usis_936; %> <% list(atan_207 ; enen)=: gelain_16; %><% list(ceonri_770; atso_148 ; eredre_533 )=: lace; %>}"))
 ----> 8         values, key = line.split("=:")
      9         values = values.strip()
     10         values = values.lstrip("(")

ValueError: too many values to unpack (expected 2)


Solution 1:[1]

From the python docs,

str.split() returns a list, and you are trying to unpack that list using two parameters, it will work when the list has two elements, but won't when the list is smaller or bigger.

For example

x, y = [1] # wont work
x, y = [1, 2, 3] # wont work

Solution 2:[2]

Have you tried debugging it?

print(line)
print(line.split("=:"))
values, key = line.split("=:")

You'll find that not every line contains exactly one =: and so line.split does not have exactly two results as your code requires.

You could add:

for line in data:
  parts = line.split("=:")
  if len(parts)!=2: continue
  values, key = parts

Solution 3:[3]

values, key = line.split("=:")

It's fairly clear from the error that line.split("=:") is splitting into a list with more than two items, and thus the unpack is failing. You can, however, force str.split to only split once.

values, key = line.split("=:", 1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriel Pellegrino
Solution 2
Solution 3 Chris