pythongenerator-expression

How to convert a string into nested dictionaries in python (Generator expression)?


here is the input string:

s = 'Iva paper 10,Nelson pens 5,Oleg marker 3,Sasha paper 7,Mark envelope 20'

I would like to have an output like this:

{'Iva': {'paper': 10},
'Mark': {'envelope': 20},
'Nelson': {'pens': 5},
'Oleg': {'marker': 3},
'Sasha': {'paper': 7}}

the code that can do that is:

for k in s.split(','):
    v = k.split(' ')
    d[v[0]] = {v[1]: int(v[2])}  

but the question is how can I do it using a Generator expression?

If thee were 2 elements('paper 5,pen 6,...') I could do this

d = dict((k, int(v)) for k, v in (e.split(' ') for e in s.split(',')))

I wonder how we can do it in this case!

thanks


Solution

  • s = 'Iva paper 10,Nelson pens 5,Oleg marker 3,Sasha paper 7,Mark envelope 20'
    
    g = dict((j, dict([(k, l)])) for i in s.split(',') for j, k, l in (i.split(' '),))
    
    #{'Iva': {'paper': '10'}, 'Nelson': {'pens': '5'}, 'Oleg': {'marker': '3'}, 'Sasha': {'paper': '7'}, 'Mark': {'envelope': '20'}}
    print(g)