intersection, union, difference, symmetric difference for dictionaries

Peter Otten __peter__ at web.de
Tue Feb 25 16:54:43 EST 2014


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
>   set(['A']) # you did set-ops, so you get a set
> 
> If dicts were to support set ops, 

They do in 2.7 and 3.x.

> the last one would be my preferred
> result.
> 
> I just had to perform set operations on a pair of dicts earlier this
> week, shrugged, and did things the manual/explicit way:
> 
>   a_dict = dict(...)
>   b_dict = dict(...)
>   a_set = set(a_dict)
>   b_set = set(b_dict)
>   added_keys = b_set - a_set
>   removed_keys = a_set - b_set
>   same_keys = a_set & b_set
>   diff_keys = a_set ^ b_set
>   all_keys = a_set | b_set

>>> a = dict.fromkeys("ab")
>>> b = dict.fromkeys("bc")
>>> a.viewkeys() - b.viewkeys()
set(['a'])
>>> a.viewkeys() & b.viewkeys()
set(['b'])
>>> a.viewkeys() ^ b.viewkeys()
set(['a', 'c'])
>>> a.viewkeys() | b.viewkeys()
set(['a', 'c', 'b'])

For 3.x replace viewkeys() with keys().

> It would save some space if I didn't have to duplicate all the keys
> into sets (on the order of 10-100k small strings), instead being able
> to directly perform the set-ops on the dicts.  But otherwise, it was
> pretty readable & straight-forward.
> 
> -tkc





More information about the Python-list mailing list