How to invert a dict in Python
Example 1: If the values in the dictionary are unique and hashable, then I can use Recipe 4.14 in the Python Cookbook, 2nd Edition.
def invert_dict(d):
return dict([(v, k) for k, v in d.iteritems()])
d = {'child1': 'parent1',
'child2': 'parent2',
}
print invert_dict(d)
{'parent2': 'child2', 'parent1': 'child1'}
Example 2: If the values in the dictionary are hashable, but not unique, I can create a dict of lists as an inverse.
def invert_dict_nonunique(d):
newdict = {}
for k, v in d.iteritems():
newdict.setdefault(v, []).append(k)
return newdict
d = {'child1': 'parent1',
'child2': 'parent1',
'child3': 'parent2',
'child4': 'parent2',
}
print invert_dict_nonunique(d)
{'parent2': ['child3', 'child4'], 'parent1': ['child1', 'child2']}
Example 3: If I am starting with a dict of lists, where lists contain unique hashable items, I can create an inverse as shown below.
def invert_dol(d):
return dict((v, k) for k in d for v in d[k])
d = {'child1': ['parent1'],
'child2': ['parent2', 'parent3'],
}
print invert_dol(d)
{'parent3': 'child2', 'parent2': 'child2', 'parent1': 'child1'}
Example 4: If I am starting with a dict of lists, where lists contain non-unique hashable items, I can create another dict of lists as an inverse.
def invert_dol_nonunique(d):
newdict = {}
for k in d:
for v in d[k]:
newdict.setdefault(v, []).append(k)
return newdict
d = {'child1': ['parent1'],
'child2': ['parent1'],
'child3': ['parent2'],
'child4': ['parent2'],
'child5': ['parent1', 'parent2'],
}
print invert_dol_nonunique(d)
{'parent2': ['child3', 'child4', 'child5'], 'parent1': ['child1', 'child2', 'child5']}
1
Comment
—
Comments feed for this post
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(4)
-
aws
(8)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(9)
-
conkeror
(2)
-
cygwin
(18)
-
datastructures
(15)
-
datetime
(3)
-
dell
(3)
-
django
(39)
-
emacs
(20)
-
files_directories
(10)
-
install_setup
(7)
-
javascript
(3)
-
keyboard
(6)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
preferences
(8)
-
processes
(3)
-
pyqt
(18)
-
python
(122)
-
ratpoison
(3)
-
regexes
(5)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(13)
-
ssh
(7)
-
subversion
(6)
-
twisted
(6)
-
ubuntu
(60)
-
urxvt
(5)
-
vxworks
(25)
-
webservices
(4)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan
#1 MartinG commented on 2008-05-01:
Thanks - your last example (invert_dol_nonunique) was exactly what I was looking for!