Reputation: 307
I have three dicts say dict_a
, dict_b
and dict_c
dict_a={'key1':a, 'key2':b, 'key3':c}
dict_b={'key1':a, 'key2':b, 'key4':d}
dict_c={'key3':c, 'key1':a, 'key5':e}
Here the keys that are represented overall are: key1, key2, key3, key4, key5 with their respective values.
What I am looking for is eg., to create a new dict (or keep the dicts) and fill the missing keys in each dict in compare to the overall keys with 0 values and the key e.g,:
dict_a={'key1':a, 'key2':b, 'key3':c, 'key4':0, 'key5':0}
dict_b={'key1':a, 'key2':b, 'key3':0, 'key4':d, 'key5':0}
dict_c={'key1':a, 'key2':b, 'key3':c, 'key4':0, 'key5':e}
I am experienced in C, and based on my "limited knowledge" in python I would run a nested for-loop with a bunch of if, else statement to solve this, however what I know is python have some tools eg. zip
, lamda
etc. to nail this in a simple way. But I don't know how to start and begin, or even if there is a library that can solve this ?
it doesen't matter if I create new dicts with the missing keys or simple replace the existing dict, both are usable.
Upvotes: 0
Views: 47
Reputation: 46901
you could do this:
all_keys = set(dict_a).union(dict_b, dict_c)
default = 0
dct_a = {key: dict_a.get(key, default) for key in all_keys}
print(dct_a) # {'key2': 'b', 'key4': 0, 'key5': 0, 'key1': 'a',
# 'key3': 'c'}
...and so on for the other dicts.
once you have collected all_keys
it's just a one-liner to create the new dictionary. dict.get
is either the value that belongs to the key - if it exists - or default
otherwise.
Upvotes: 2
Reputation: 1258
keys=set(dict_a).union(dict_b, dict_c)
for a in keys:
if a not in dict_a.keys():
dict_a[a]=0
if a not in dict_b.keys():
dict_b[a]=0
if a not in dict_c.keys():
dict_c[a]=0
Using sets to avoid having duplicates, we get all the keys. Now we know all the keys there are. Now we check if any of these keys are not in any of the dicts and if they are not, we add them with the value 0.This will give your desired output
Upvotes: 0
Reputation: 152765
You could create a union of your keys and then just create new dictionaries containing all keys that you update with your previous values.
all_keys = set(dict_a).union(dict_b, dict_c)
new_dict_a = dict.fromkeys(all_keys, 0)
new_dict_a.update(dict_a)
print(new_dict_a)
# {'key1': 'a', 'key2': 'b', 'key3': 'c', 'key4': 0, 'key5': 0}
The same for the other dicts:
new_dict_b = dict.fromkeys(all_keys, 0)
new_dict_b.update(dict_b)
new_dict_c = dict.fromkeys(all_keys, 0)
new_dict_c.update(dict_c)
The dict.fromkeys
creates a new dictionary containing all the specified keys with a default value (in this case 0
) and then the update
overwrites the values that were already in the original dictionary.
Upvotes: 2