This is an extension of this question: How to split a string within a list to create key-value pairs in Python
The difference from the above question is the items in my list are not all key-value pairs; some items need to be assigned a value.
I have a list:
list = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
I would like to create a dictionary:
dict = { 'abc':'ddd', 'ef':1, 'ghj':1, 'jkl':'yui', 'rty':1 }
I was thinking something along the lines of:
a = {}
for item in list:
if '=' in item:
d = item.split('=')
a.append(d) #I don't I can do this.
else:
a[item] = 1 #feel like I'm missing something here.
For each split "pair", you can append [1]
and extract the first 2 elements. This way, 1 will be used when there isn't a value:
print dict((s.split('=')+[1])[:2] for s in l)
I would be using something similar to the post you linked.
d = dict(s.split('=') for s in a)
If you combine what you can learn from this post -- that is to use lists to create dictionaries -- and from using if/else in Python's list comprehension, you can come up with something like this:
d = dict(s.split("=", maxsplit=1) if "=" in s else [s, 1] for s in l)
What this does is add 1
to the end of the split list if there is no equal sign in it.
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}
'ef'
which does not have equal sign, we will have to fix thatdict
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With