join dictionaries using keys from one & values

Alex Martelli aleax at mail.comcast.net
Tue Dec 6 00:47:29 EST 2005


ProvoWallis <gshepherd281 at earthlink.net> wrote:
   ...
> The keys in the new dictionary would be the keys from the old
> dictionary one (dict1) and the values in the new dictionary would be
> the keys from the old dictionary two (dict2). The keys would be joined
> by matching the values from dict1 and dict2. The keys in each
> dictionary are unique.

...but are the VALUES unique...?  That's the crucial issue and you don't
mention anything about it.

> dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}
> 
> dict2 = {5.01:'bbb', 6.01:'ccc', 7.01:'aaa'}
> 
> dict3 = {1 : 5.01, 3 : 6.01, 2 : 7.01}

But what if in dict1 both keys 2 and 3 had a corresponding value of
'ccc' -- what would you want as a result then?  What if key 1 had a
corresponding value of 'ddd' -- not a value in dict2; what would you
want THEN?  Without a more complete specification, it's impossible to
tell, and one key Python principle is "in the face of ambiguity, refuse
the temptation to guess".

If values are assured to be unique, and the sets of values of the two
dictionaries are assured to be identical, then the suggestion (already
given in another post) to invert dict2 is a good idea, i.e., as a
function:

def PWmerge(d1, d2):
  invd = dict((v2, k2) for k2, v2 in d2.iteritems())
  return dict((k1,invd[v1]) for k1,v1 in d1.iteritems())

but without all of the above assurances, different tweaks may be needed
depending on what exactly you want to happen in the several "anomalous"
cases.


Alex



More information about the Python-list mailing list