intersection, union, difference, symmetric difference for dictionaries

Tim Chase python.list at tim.thechases.com
Tue Feb 25 16:03:51 EST 2014


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

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