Filter common dictionary keys in a dictionary

How can I filter all public dictionary keys that exist in other dictionary dictionary keys in the parent dictionary

d = {
  '0': {'key_x': 0, 'key_y': 15, 'key_z': 41}
  '1': {'key_x': 5, 'key_y': 22}
  '2': {'key_x': 6, 'key_y': 41}
}

result ['key_x', 'key_y']

current decision

intersect = {}
for k in corner_values.keys():
    for j in corner_values[k]:
        if j not in intersect:
            intersect[j] = 1
        else:
            intersect[j] += 1

for k in intersect:
    if intersect[k] != len(corner_values.keys()):
        del intersect[k]

Is there a simpler solution for this?

+4
source share
3 answers

You can mapdictionaries on set, and then reduceusing set.intersection:

>>> from functools import reduce # if you are using Python 3
>>> d = {                       
...   '0': {'key_x': 0, 'key_y': 15, 'key_z': 41},
...   '1': {'key_x': 5, 'key_y': 22},
...   '2': {'key_x': 6, 'key_y': 41}
... }
>>> reduce(set.intersection, map(set, d.values()))
{'key_x', 'key_y'}

Note. In Python 3, reducewas ported to functools.

Update: as shown in @John's answer , it set.intersectioncan handle an arbitrary number of sets, so reduceit’s not even required. Simplyset.intersection(*map(set, d.values()))

+5
source

set.intersection, . :

set.intersection(*(set(x) for x in d.itervalues()))

, :

(set(x) for x in d.itervalues())

, :

{'key_x', 'key_y'}, {'key_x', 'key_y', 'key_z'}, {'key_x', 'key_y'}

Python 3 :

map(set, d.values())

Python 2 map , list, ( values() itervalues()).

set.intersection ( *) .

+3

Alternative with pandas, keys do not need to be ordered:

import pandas as pd

list(pd.DataFrame(d).dropna().index)

#['key_x', 'key_y']
+1
source

All Articles