How can I update a dictionary with missing key present in a separate list in python?

Viewed 31

Hi all I have a dictionary and a list of key

Diz = {'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7}}

L = ['Triangle','Traingle5R','Rectangle','CircularMMW','CircularHMW']

I would like to fill the dictionary with the missing key present in the list and set them at Zero, by keeping the older one with their respective value

Diz = {'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7}}
L = ['Triangle','Traingle5R','Rectangle','cMMW','cHMW',"sRib"]

I am trying this code but it set all key at zero also the one that has a starting value

for el in L:
    for k,v in Diz.items():
        for k2,v2 in v.items():
            if el not in k2:
                Diz[k][el] = 0

print(Diz)

I would like to have this output

Diz = {'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9,'Triangle':0,'Traingle5R':0,'Rectangle':0,'cMMW','cHMW}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7,'Triangle':0,'Traingle5R':0,'Rectangle':0,"cHMW":0}}

And at the end I would also produce a table in a txt file for each line a key and dictionary value.

1 Answers

You can iterate through each keys of the dictionary, and use dict.get for inner dictionary passing 0 as default value and assign it back to the inner dictionary.

for key in Diz:
    for item in L:
        Diz[key][item] = Diz[key].get(item, 0)

OUTPUT:

{'X080213_2_0004_2_000005': {'cHMW': 1, 'sRib': 9, 'Triangle': 0, 'Traingle5R': 0, 'Rectangle': 0, 'cMMW': 0}, 'X280113_1_0002_2_000003': {'cMMW': 1, 'sRib': 7, 'Triangle': 0, 'Traingle5R': 0, 'Rectangle': 0, 'cHMW': 0}}
Related