Friday, September 11, 2009

python dictionary little hack

The situation is this: Let's say I have a dictionary that maps to dictionaries.
I want to get a list of all the keys in the secondary dictionaries, take out duplicates and return as a list.

So let's say we have something like this:
d1 = { 1 : "aaa", 2 : "bbb" }
d2 = { 22 : "yyy", 33 : 'zzzzz' }
d3 = { 141 : 'xyz', 123 : 'abc', 231 : 'lmnop' }
myd2d = {
'a' : d1,
'b' : d3,
'c' : d2 }
The desired answer is
[1,2,22,33,141,123,231]
Not necessarily in that order. The straightforward way to do it would be:
result = []
for k,v in myd2d.iteritems():
for mykey in v.keys():
result.append( mykey )
I suppose the other way might be more pythonic:
r = sum( (v.keys() for k,v in myd2d.iteritems()), [] )

No comments: