How to get all keys in 2d dict python

I have a form dictionary:

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

So, let's look at the keys of the second degree.

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

Thus, the total number of unique second-order keys:

 1,2,3 

Now I want to change 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}} 

Thus, basically all second-order keys are missing from a particular 2d dict .. add this key with a value of 0.

What is the pythonic way to do this? Thanks

+4
source share
4 answers
 keyset = set() for k in d: keyset.update(d[k]) for k in d: for kk in keyset: d[k].setdefault(kk, 0) 
+9
source
 In [25]: d = {123:{2:1,3:1}, 124:{3:1}, 125:{2:1},126:{1:1}} In [26]: se=set(y for x in d for y in d[x]) In [27]: for x in d: foo=se.difference(d[x]) d[x].update(dict(zip(foo,[0]*len(foo)))) ....: ....: In [30]: d Out[30]: {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}} 

here use the difference in the settings to get the missing keys, and then update() dict:

 In [39]: for x in d: foo=se.difference(d[x]) print foo # missing keys per dict set([1]) set([1, 2]) set([1, 3]) set([2, 3]) 
+3
source

I like the decision of Ashvini Chaudhary.

I edited it to include all the sentences in the comment with other minor changes so that it looks as I would prefer:

Edited (includes a proposal by Stephen Rumbalski to this answer).

 all_second_keys = set(key for value in d.itervalues() for key in value) for value in d.itervalues(): value.update((key,0) for key in all_second_keys if key not in value) 
+2
source
 import operator second_order_keys = reduce(operator.__or__, (set(v.iterkeys()) for v in d.itervalues())) for v in d.itervalues(): for k in second_order_keys: v.setdefault(k, 0) 

Or, in Python 3:

 from functools import reduce import operator second_order_keys = reduce(operator.__or__, (v.keys() for v in d.values())) for v in d.values(): for k in second_order_keys: v.setdefault(k, 0) 
+1
source

Source: https://habr.com/ru/post/1440606/


All Articles