Skip to content

Instantly share code, notes, and snippets.

@infinityplusone
Created December 30, 2011 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infinityplusone/1537679 to your computer and use it in GitHub Desktop.
Save infinityplusone/1537679 to your computer and use it in GitHub Desktop.
Expanded dictionary inversion in Python (July 11, 2006)
# This is actually just a variant of a recipe I posted to ActiveState over five years ago.
# Location: http://code.activestate.com/recipes/496881-expanded-dictionary-inversion/
# the actual code that matters here. first argument must be a dictionary.
def invert(d, unique=False):
dd = {}
for k, v in d.items():
if not isinstance(v, (tuple, list)): v = [v]
if unique:
dd.update( [(vv, dd.setdefault(vv, []) + [k]) for vv in v] )
else:
[dd.setdefault(vv, []).append(k) for vv in v]
return dd
# some example dictionaries to test out
def test():
examples = [
{ 'A': (1,), 'C': (3, 3), 'B': (2, 4) },
{ 'A': [3, 2, 1], 'C': [3, 2], 'B': [1, 4] },
{ 'A': 2, 'C': 4, 'B': 5, 'D': 5 },
{ 'C': (4, 1 , 4, 9), 'B': 5, 'D': [5, 3], 'E': '9' },
{ 'A': [1, 2, 3], 'B': 4 }
]
for e in examples:
a = invert(e)
b = invert(e, 1)
print '\n'
print ' original:', x
print ' inverted:', a
print ' + unique:', b
if a!=b:
print ' ---------> Find the difference!'
### test() will output the following
'''
original: {'A': [1, 1], 0: 'X', 3: [5, 3], 1: None}
inverted: {1: ['A'], 2: ['B'], 3: ['C', 'C'], 4: ['B']}
+ unique: {1: ['A'], 2: ['B'], 3: ['C'], 4: ['B']}
---------> Find the difference!
original: {'A': [1, 1], 0: 'X', 3: [5, 3], 1: None}
inverted: {1: ['A', 'B'], 2: ['A', 'C'], 3: ['A', 'C'], 4: ['B']}
+ unique: {1: ['A', 'B'], 2: ['A', 'C'], 3: ['A', 'C'], 4: ['B']}
original: {'A': [1, 1], 0: 'X', 3: [5, 3], 1: None}
inverted: {2: ['A'], 4: ['C'], 5: ['B', 'D']}
+ unique: {2: ['A'], 4: ['C'], 5: ['B', 'D']}
original: {'A': [1, 1], 0: 'X', 3: [5, 3], 1: None}
inverted: {1: ['C'], 3: ['D'], 4: ['C', 'C'], 5: ['B', 'D'], 9: ['C'], '9': ['E']}
+ unique: {1: ['C'], 3: ['D'], 4: ['C'], 5: ['B', 'D'], 9: ['C'], '9': ['E']}
---------> Find the difference!
original: {'A': [1, 1], 0: 'X', 3: [5, 3], 1: None}
inverted: {1: ['A'], 2: ['A'], 3: ['A'], 4: ['B']}
+ unique: {1: ['A'], 2: ['A'], 3: ['A'], 4: ['B']}
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment