Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intersection across multiple dictionary keys

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)))

1 Answers

You can convert the dicts directly to sets, instead of dict_keys objects, which can then be passed to set.intersetcion():

dicts = [{'a': 1, 'b': 2, 'c': 1, 'd': 8}, {'c': 4, 'b': 3}, {'a': 9, 'b': 14}]
set.intersection(*map(set, dicts))
# {'b'}
like image 116
Mark Avatar answered Jun 30 '26 06:06

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!