Amelia N Chu Amelia N Chu - 6 months ago 10
Python Question

How to create a dictionary from a list with a list of keys only and key-value pairs (Python)?

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.

Answer

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)