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 n
Solution 1:
keyset = set()
forkin d:
keyset.update(d[k])
forkin d:
forkkin keyset:
d[k].setdefault(kk, 0)
Solution 2:
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 set difference to get the missing keys and then update()
the dict:
In [39]: for x in d:
foo=se.difference(d[x])
print foo # missing keys per dictset([1])
set([1, 2])
set([1, 3])
set([2, 3])
Solution 3:
I like the solution of Ashwini Chaudhary.
I edited it to incorporate all the suggestions in the comments with other minor changes for it to look how I would prefer it:
Edited (incorporates the suggestion of Steven Rumbalski to this answer).
all_second_keys = set(keyfor value in d.itervalues() forkeyin value)
for value in d.itervalues():
value.update((key,0) forkeyin all_second_keys ifkeynotin value)
Solution 4:
importoperator
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
importoperator
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)
Post a Comment for "How To Get All The Keys In A 2d Dict Python"