There is a straight forward way to update an existing or empty directory from given a list of keys. In the first example below, we update dict only with keys, which were not already present. Notice that the key ‘a’ did get change and ‘z’ did not get deleted – they were left alone. The second example, basically initializes an empty dict object. Whereas, the third example creates a new dict object which did not exist before.
Note that, default_value is used here as a static value – just for simplicity and to convey the idea. You can use any value, as per your requirement.
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} |