Welcome, guest | Sign In | My Account | Store | Cart

Invert a dictionary that has lists as its values. For example, convert {A:[1,2,3], B:[4]} into {1:A, 2:A, 3:A, 4:B}

Python, 2 lines
def invert(d):
    return dict( (v,k) for k in d for v in d[k] )

This assumes that all the items in the value-lists are unique.


Jason Drew 18 years, 6 months ago  # | flag

Covered more thoroughly. This recipe is already here, with a few other variants (including for recurring values): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252143

Jason Drew 18 years, 6 months ago  # | flag

Sorry ... ... just noticed the twist that this version is useful when values are lists! (Still, the link to the related recipe is useful.) Thanks.

Created by Arkady Pogostkin on Tue, 24 May 2005 (PSF)
Python recipes (4591)
Arkady Pogostkin's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks