Here are the step-by-step approach.
In [50]: mylist = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
In [51]: [element.split('=') for element in mylist]
Out[51]: [['abc', 'ddd'], ['ef'], ['ghj'], ['jkl', 'yui'], ['rty']]
In [52]: [element.split('=') + [1] for element in mylist]
Out[52]: [['abc', 'ddd', 1], ['ef', 1], ['ghj', 1], ['jkl', 'yui', 1], ['rty', 1]]
In [53]: [(element.split('=') + [1])[:2] for element in mylist]
Out[53]: [['abc', 'ddd'], ['ef', 1], ['ghj', 1], ['jkl', 'yui'], ['rty', 1]]
In [54]: dict((element.split('=') + [1])[:2] for element in mylist)
Out[54]: {'abc': 'ddd', 'ef': 1, 'ghj': 1, 'jkl': 'yui', 'rty': 1}
- In order to convert your list in line 50 to a dictionary, you will need to convert it to the list in line 53.
- Line 51. The first step is to split each element in the list by the equal sign. Each element now is transformed into a list of 1- or 2 elements. Notice that some element like
'ef'
which does not have equal sign, we will have to fix that
- Line 52. Next, we append 1 to each sub list. That should take care of the sublists with 1 element, but making some sublist 3 element long
- Line 53: We normalize all sublist into 2-element ones by taking just the first two element and discard the third one if applicable. This list now is in the correct format to convert into a dictionary
- Line 54. The last step is to take this list and convert it into a dictionary. Since the
dict
class can take a generator expression, we can safely remove the square brackets.
With that, here is the snippet:
mylist = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
mydict = dict((element.split('=') + [1])[:2] for element in mylist)