-
-
Save aarshtalati/a79f0efaef85e0a4c0568efadf512b41 to your computer and use it in GitHub Desktop.
Update dictionary form list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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