intersection, union, difference, symmetric difference for dictionaries

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 25 18:10:29 EST 2014


On Tue, 25 Feb 2014 15:03:51 -0600, Tim Chase wrote:

> On 2014-02-25 14:40, Skip Montanaro wrote:
>> What's the correct result of evaluating this expression?
>> 
>> {'A': 1} | {'A': 2}
>> 
>> I can see (at least) two possible "correct" answers.
> 
> I would propose at least four:
> 
>   {'A': 1}   # choose the LHS
>   {'A': 2}   # choose the RHS
>   {'A': (1,2)} # a resulting pair of both 

Should that value be a tuple, a list or a set?


>   set(['A']) # you did set-ops, so you get a set

Option 5: raise an exception if the values are different.

Option 6: "or" the values, so that the LHS value is used only if it is 
truthy, otherwise the RHS value is used. That is:

    {'A': leftdict['A'] or rightdict['A']}


I don't really understand the use-case behind Option 6, but there is a 
recent thread on python-ideas at python.org where somebody proposed that as 
the Obviously One True And Correct behaviour for dict intersection.



> If dicts were to support set ops, the last one would be my preferred
> result.

What, getting a set back?

No, I disagree. If you want a set, it's easy to do:

dicta.keys() | dictb.keys()

(In Python 2, use viewkeys instead.)


gives you a set of the intersection of the keys. The only point of having 
dicts support set-like operations directly is if you get a dict back.

All of these operations are quite simple to write, so personally I would 
recommend people just add their own helper function with the behaviour 
they prefer.


-- 
Steven



More information about the Python-list mailing list