Cloud Stack Ninja

I have many dictionaries:

dicts = [{'a': 1, 'b': 2, 'c': 1, 'd': 8}, {'c': 4, 'b': 3}, {'a': 9, 'b': 14}, ...]

I want to find out which keys they have in common.

So, f(dicts) == {'b'} in this case.

I had assumed

set.intersection(*map(dict.keys, dicts))

Would work, but I get the error

TypeError: descriptor 'intersection' for 'set' objects doesn't apply to a 'dict_keys' object

So it looks like dict.keys returns a dict_keys object, that set.intersection refuses to handle.

Is there an equally succinct way to get the collective intersection of some dict_keys? Or am I forced to reduce with &?

import functools
set(functools.reduce(lambda a, b: a & b, map(dict.keys, dicts)))

Read more here:

Content Attribution

This content was originally published by theonlygusti at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: