Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new dictionary with common subkey

If I have a dictionary, as follows:

{
    'key1':
        {
            'foo': 1233,
            'bar': 1234,
            'baz': 122
        },
    'key2':
        {
            'foo': 113,
            'bar': 333
        }
}

how can i return a new dictionary with the following result

{
    'key1':
        {
            'foo': 1233,
            'bar': 1234
        },
    'key2':
        {
            'foo': 113,
            'bar': 333
        }
}

I want the sub-dictionaries (is this the right term?) of 'key1' and 'key2' have the same keys

like image 285
Jeffrey04 Avatar asked Apr 09 '14 09:04

Jeffrey04


1 Answers

This should do it:

>>> d = { 'key1': { 'foo': 1233, 'bar': 1234, 'baz': 122 }, 'key2': { 'foo': 113, 'bar': 333 } }
>>> keys = (x.keys() for x in d.itervalues())
>>> common_keys = set(next(keys)).intersection(*keys)
>>> {k : {k_: v[k_] for k_ in common_keys} for k, v in d.iteritems()}

{'key2': {'foo': 113, 'bar': 333},
 'key1': {'foo': 1233, 'bar': 1234}}
like image 134
Ashwini Chaudhary Avatar answered Sep 28 '22 12:09

Ashwini Chaudhary