Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all the keys in a 2d dict python

I have a dictionary of form:

d = {123:{2:1,3:1}, 124:{3:1}, 125:{2:1},126:{1:1}}

So, lets look into 2nd degree keys..

123--> 2,3
124--> 3
125--> 2
126--> 1

So total number of unique 2nd order keys are:

1,2,3

Now, i want to modify this dict as

 d = {123:{1:0,2:1,3:1}, 124:{1:0,2:0,3:1}, 125:{1:0,2:1,3:0},126:{1:1,2:0,3:0}}

So basically all the 2nd order keys absent in a particular 2d dict.. add that key with value 0.

What is the pythonic way to do this? Thanks

like image 206
frazman Avatar asked Dec 07 '22 11:12

frazman


1 Answers

keyset = set()
for k in d:
    keyset.update(d[k])

for k in d:
    for kk in keyset:
        d[k].setdefault(kk, 0)
like image 189
nneonneo Avatar answered Dec 15 '22 13:12

nneonneo