Create/Update dictionary form list


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.

>>> 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}

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s