PYPL - 2 years ago 93
Python Question

# Filter common sub-dictionary keys in a dictionary

How do i filter all common sub dictionary keys that exists in other sub 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 solution is

``````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 any simpler solution for this?

You can `map` the dictionaries to `set` and then `reduce` using `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, `reduce` has been moved to `functools`.

Update: As seen in @John's answer, `set.intersection` can handle an arbitrary number of sets, so the `reduce` is not even necessary. Just `set.intersection(*map(set, d.values()))`

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download