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
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With