Tuesday 14 January 2020

Failure converting complex code to a list comprehension

NB: None of the suggested answers work for me as they are for-loop driven (which I already have working) and don't explain what is wrong with the list comprehension version.


I am trying to transform

('name:80', 'desc:100')

into

{'name': 80, 'desc': 100}

A working for-loop:

new_wrap = {}
for item in wrap:
    k, v = item.split(':')
    new_wrap[k] = int(v)
wrap = new_wrap

a non-working list-comprehension:

wrap = dict([
    (k, int(v))
    for item in wrap
    for (k, v) in item.split(':')
    ])

which gives

Traceback (most recent call last):
  File ..., line ..., in ...
    for (k, v) in item.split(':')
ValueError: too many values to unpack

What am I doing wrong?



from Failure converting complex code to a list comprehension

No comments:

Post a Comment