Reputation: 351
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.
Upvotes: 5
Views: 3995
Reputation: 2701
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.
Upvotes: 5
Reputation: 1818
input_list = ['abc=ddd', 'ef', 'ghj', 'jkl=yui', 'rty']
output_dict = {}
for item in input_list:
item_split = item.split('=')
key = item_split[0]
value = item_split[1] if len(item_split)>1 else 1
output_dict[key] = value
a bit more concisely
for item in input_list:
i_s = item.split('=')
output_dict[i_s[0]] = i_s[1] if len(i_s)>1 else 1
This has the advantage that it doesn't append an extra element to each list created by splitting the elements of the input_list. Though, list comprehensions can be faster than a for
loop
Upvotes: 1
Reputation: 40688
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)
Upvotes: 1
Reputation: 12772
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)
Upvotes: 13