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}
1 2 | 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.
Tags: shortcuts
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
Sorry ... ... just noticed the twist that this version is useful when values are lists! (Still, the link to the related recipe is useful.) Thanks.