|
Description:
Invert different types of dictionaries with mixed data types as values.
Source: Text Source
def invert1(d):
dd = {}
for k, v in d.items():
if not isinstance(v, (tuple, list)): v = [v]
dd.update( [(vv, dd.setdefault(vv, []) + [k]) for vv in v] )
return dd
def invert2(d):
dd = {}
for k, v in d.items():
if not isinstance(v, (tuple, list)): v = [v]
[dd.setdefault(vv, []).append(k) for vv in v]
return dd
Discussion:
I just wanted to add a few more possibilities to the inverters in these recipes:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252143
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415100
The difference between these two can be seen using {'A': [1, 1]}:
invert1({'A': [1, 1]}) --> {1: ['A']}
invert2({'A': [1, 1]}) --> {1: ['A', 'A']}
You can try it out with these as well:
{'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}
{'A': 2, 'C': 4, 'B': 5, 'D': [5, 3]}
{'A': [1, 2, 3], 'B': 4}
|