0

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]}
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • I edited it into the question, but how does it matter? `l[0]` should give complete information, no? – CIsForCookies Aug 28 '18 at 08:58
  • So you want to turn the first element of `l` into a dict with a single key/value pair? That seems odd. What's the point of a dict with only a single key inside of it? It would make more sense to turn the whole list `l` into a dict, no? – Aran-Fey Aug 28 '18 at 08:58
  • The `len` return two and it returns two values, seems like it should be. – Bernhard Aug 28 '18 at 08:59
  • @Aran-Fey I'm testing it for the 1st element. When I'll fix this issue, I'll expand it for the entire list (`l` can be much bigger) – CIsForCookies Aug 28 '18 at 09:02

1 Answers1

1

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}
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • 2
    Surely `(s.split(',', 1) for s in l)` would've been more readable than this weird `map(str.split, l, repeat(','), repeat(1))` construct? – Aran-Fey Aug 28 '18 at 09:04
  • 1
    @Aran-Fey Not for *me*. But you may use what you choose. I don't like a lot of syntax that gets out of hand quickly. Maybe it isn't that weird and you're just no used to it? Anyway, I'd prefer to use `partial` if not the `map` - but honestly its very readable to me (`repeat` in `map` is just a constant binding on a parameter). – Reut Sharabani Aug 28 '18 at 09:05