I would like to create a dictionary of values ββfrom a split () sequence without spaces.
If I had a list of lines that were formatted like this:
lines = ['Item1 = A Item2 = B Item3 = C',
'Item4 = D Item5 = E']
I know how to get pairs by spaces> 2:
s = [y for x in lines for y in x.split(' ') if y]
This returns another list of rows with pairs:
s = ['Item1 = A', 'Item2 = B', 'Item3 = C', 'Item4 = D', 'Item5 = E']
So far so good. Now from here you need to break the pairs into =, the left side - keyand the right side - value. I can do it:
t = [y.split('=') for x in lines for y in x.split(' ') if y]
This returns another list of strings with broken pairs:
t = ['Item1 ', ' A', 'Item2 ', ' B', 'Item3 ', ' C', 'Item4 ', 'D', 'Item5 ', ' E']
Now each element has either a trailing or leading space. This can be easily fixed by updating the line of the last list so that:
t = [z.strip() for x in lines for y in x.split(' ') for z in y.split('=') if y]
To make this dictionary, I know to call the generator expression:
d = dict(y.split('=') for x in lines for y in x.split(' ') if y)
key value. z.strip(), :
ValueError: dictionary update sequence element #0 has length 5; 2 is required
:
dict() strip() split('=') ? strip() dict()?