Python: Too many values to unpack (dictionary)
Question: I'm trying to add key-value pairs to a dictionary by pairing two and two lines
from a text file. Why does this not work?

    
    
    newdata = {}
    os.chdir("//GOLLUM//tbg2//tbg2//forritGB")
    f = open(filename)
    for line1, line2 in f.readlines():
        newdata[line1] = line2
    

edit: The error I get is

    
    
    ValueError: too many values to unpack
    


Answer: You are reading all lines, and assigning the first line (a sequence) to two
variables. This only works if the first line consists of 2 characters. Use the
file as an iterator instead:

    
    
    newdata = {}
    os.chdir("//GOLLUM//tbg2//tbg2//forritGB")
    with open(filename) as f:
        for line1 in f:
            newdata[line1.strip()] = next(f, '').strip()
    

Here `next()` reads the next line from the file.

The alternative would be to use a pair-wise recipe:

    
    
    from itertools import izip_longest
    
    def pairwise(iterable):
        return izip_longest(*([iter(iterable)] * 2), '')
    
    newdata = {}
    os.chdir("//GOLLUM//tbg2//tbg2//forritGB")
    with open(filename) as f:
        for line1, line2 in pairwise(f):
            newdata[line1.strip()] = line2.strip()
    

Note the `str.strip()` calls, to remove any extra whitespace (including the
newline at the end of each line).

