Search code examples
pythondictionaryiterable-unpacking

dict comprehension failure - not enough values to unpack


I want to create a dict from a list of strings:

print(l)
print(l[0])                            # 1st string in list
print(l[0].split(',',1))
print(len(l[0].split(',',1)))
d = {int(k):v for k,v in l[0].split(',',1)}

['0,[7,2,5,7]', '1,[7,18,6,2]']
0,[7,2,5,7]
['0', '[7,2,5,7]']
2

However, I get d = {int(k):v for k,v in l[0].split(',',1)} ValueError: not enough values to unpack (expected 2, got 1)

I can't understand why, as l[0].split(',',1) returns 2 values, as can be seen from my previous checks (print(len(l[0].split(',',1))) returns 2)

My desired output:

d = {0 : [7,2,5,7]}

Solution

  • It returns two values but the loop expects a list of two values.

    You have this: [x, y]

    But the code expects this: [[x, y]]

    You could do:

    from itertools import repeat
    items = map(str.split, l, repeat(','), repeat(1))
    d = {int(k):v for k,v in items}
    

    Note that you'll get all the data and not just one item.

    You may want to parse the list using ast.literal_eval because currently its a string:

    import ast
    from itertools import repeat
    items = map(str.split, l, repeat(','), repeat(1))
    d = {int(k):ast.literal_eval(v) for k,v in items}