Skip to content

Instantly share code, notes, and snippets.

@aarshtalati
Last active October 13, 2018 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarshtalati/a79f0efaef85e0a4c0568efadf512b41 to your computer and use it in GitHub Desktop.
Save aarshtalati/a79f0efaef85e0a4c0568efadf512b41 to your computer and use it in GitHub Desktop.
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