Skip to content

Instantly share code, notes, and snippets.

@aarshtalati
Last active Oct 13, 2018
Embed
What would you like to do?
Update dictionary form list
>>> my_list = ['a', 'b', 'c', 'd']
# existing dict object which already has some values in it
>>> my_dict = { 'a' : 5 , 'z': 10 }
>>> default_value = -1
>>> my_dict.update({k: default_value for k in my_list if k not in my_dict.keys()})
>>> my_dict
{'a': 5, 'c': -1, 'z': 10, 'b': -1, 'd': -1} # original values are left as-is
# also works with empty dict
>>> my_dict = {}
>>> my_dict.update({k: default_value for k in my_list if k not in my_dict.keys()})
>>> my_dict
{'a': -1, 'c': -1, 'b': -1, 'd': -1}
# even if the dict object did not exist
>>> x = dict((k, default_value) for k in my_list)
>>> x
{'a': -1, 'c': -1, 'b': -1, 'd': -1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment