Retreive the unique keys (second dimension) of a 2 dimensional dictionary in python?
Question: I have a a 2d dictionary (named d2_dic). I know how to get the unique keys
(It's always unique) of the first dimension by d2_dic.keys(). But how do I get
the unique keys of the second dimension?

    
    
    from collections import defaultdict
    d2_dic = defaultdict(dict)
    d2_dic['1']['a'] = 'Hi'
    d2_dic['1']['b'] = 'there'
    d2_dic['2']['a'] = '.'
    

To get the unique keys in the first dimension, i just need to do a
d2_dic.keys() {o/p = 1,2} How do I retreive the unique keys of the second
dimension??

I need an o/p of [a,b]


Answer: The entity `d2_dic['1']` is itself a dictionary (same with `d2_dic['2']`). So
you can use `d2_dic['1'].keys()` to get the keys for that dictionary. If you
want a list of all the possible keys in the second dimension then you could do
the following.

    
    
    mykeys = []
    for k in d2_dic.keys() :
        mykeys.extend(d2_dic[k].keys())
    # this removes duplicates but destroys order
    mykeys = list(set(mykeys))
    print mykeys # ['a', 'b']
    

Apparently, you can also do this in one line with list comprehension, as per
the comment by @vaultah: `mykeys = list({x for d in d2_dic.values() for x in
d.keys()})`.

You have to be careful with this though, because `d2_dic['2'][mykeys[1]]` will
resault in `KeyError: 'b'`. You may want to wrap some of your code in try and
except statements. For example:

    
    
    for i in d2_dic.keys() :
        for j in mykeys :
            try : 
                d2_dic[i][j]
            except KeyError :
                d2_dic[i][j] = None
            print i, j, d2_dic[i][j]
    

Note that these print statements won't work in python 3

