How to correct ValueError: not enough values to unpack (expected 2, got 1)

Viewed 139

When I am trying to print

import collections 
sentences = collections.defaultdict(list)
unique_suffixes = set()
with open ('file.txt', 'r') as s:
    for line in s:
        start, end = line.split(' ', maxsplit=1)

I am throwing "ValueError: not enough values to unpack (expected 2, got 1)". based on the last line of the code.

I found a couple of questions though they have good information they are helpful to me in this case

2 Answers

That is due to the fact that your last line yields a list with two elements.

So the following must solve your issue:

import collections 
sentences = collections.defaultdict(list)
unique_suffixes = set()
with open ('input.txt', 'r') as s:
    for line in s:
        data = line.split(' ', maxsplit=1)
        start = data[0]
        end = data[1]

Try this: if line have no space, it will take same word as start and end.

import collections 
sentences = collections.defaultdict(list)
unique_suffixes = set()
my_list = []
with open ('file.txt', 'r') as s:
    for line in s:
        data = line.split(' ', maxsplit=1)
        start = data[0]
        end = data[-1]
        my_list.append((start, end))

-1 index in python means take the first element in reverse order of the list.

To write it as a csv file:

import csv
with open('outfile.csv','w') as f:
    out = csv.writer(f)
    out.writerow(['titleA', 'titleB'])
    out.writerows(my_list)
Related