Finding items not in 2 lists/dictionaries

Alex Martelli aleax at aleax.it
Fri May 2 03:08:50 EDT 2003


<posted & mailed>

Robin Siebler wrote:

> On page 15 of the Python Cookbook, it shows how to find all of the
> common items in 2 dictionaries.  How would I find all of the items
> that are *not* in both dictionaries (or lists)?

The CB p15 solution actually deals with keys, as the problem statement
shows, although the discussion does debatably talk of items.  Anyway,

[k for k in dict1 if k not in dict2] + [k for k in dict2 if k not in dict1]

is the "one obvious way" to get a list of keys that are in either one dict 
and not in the other.  Beware: this would be SLOW for two long lists -- 
making dicts out of the lists (e.g. with Python 2.3 dict.fromkeys, or in 
2.2 with auxdict1=dict(zip(list1,list1)) &c, is likely to speed things up
dramatically unless the lists are quite short.


Alex





More information about the Python-list mailing list