intersection, union, difference, symmetric difference for dictionaries

Peter Otten __peter__ at web.de
Tue Feb 25 21:53:18 CET 2014


mauro wrote:

>  Dictionaries and sets share a few properties:

> - Dictionaries keys are unique as well as sets items
> - Dictionaries and sets are both unordered
> - Dictionaries and sets are both accessed by key

but sets have no values

> - Dictionaries and sets are both mutables

but frozensets also have the operations mentioned in the subject.

> So I wonder why operations such us intersection, union, difference,
> symmetric difference that are available for sets and are not available
> for dictionaries without going via key dictviews.

How would you define them? 

E. g.

{1, 2} & {2, 3} == {2}

but

{1:"a", 2:"b", 3:"c"} & {2:"b", 3:"e", 4:"f"} == ???

The most obvious result is probably the empty dict {2:"b"}, i. e.

a & b is defined as dict(a.items() & b.items())

Frankly, I don't do that a lot. So what's your use-case?





More information about the Python-list mailing list