Reputation: 724
I have a dictionary params
. Now I would like to create a list (of dictionaries) from params
. This list has either one or two elements as sometimes I dont have both key/value pairs in params
. So I would like to only add these element to the list if they exist in params
. Is there a simple way to do that? I mean I know I could do an if else statement but I would like to use as little code as possible.
params={'key1':'bla1', 'key2':'bla2'}
I know this works but is there something with less code
if 'key1' not in params:
list_ = [{'val2': params['key2']}]
elif 'key2' not in params:
list_ = [{'val1': params['key1']}]
else:
list_ = [{'val1': params['key1']}, {'val2': params['key2']}]
Upvotes: 0
Views: 230
Reputation: 1603
You can use a list comprehension :
list_ = [{k:v} for k,v in params.items()]
Then rename the keys at the end :
list_['val1']=list_['key1']
del list_['key1']
list_['val2']=list_['key2']
del list_['key2']
Or you can just rename the keys during the list comprehension with a dictionnary giving the actual keys.
names={'key1':'val1', 'key2':'val2'}
list_ = [{names[k]:v} for k,v in params.items()]
Upvotes: 1