1
|
|
|
from collections import Iterable, OrderedDict |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
def inverse_dicts(*dicts): |
5
|
|
|
""" |
6
|
|
|
Inverts the dicts, e.g. {1: 2, 3: 4} and {2: 3, 4: 4} will be inverted |
7
|
|
|
{2: [1, 2], 4: [3, 4]}. This also handles dictionaries with Iterable items |
8
|
|
|
as values e.g. {1: [1, 2, 3], 2: [3, 4, 5]} and |
9
|
|
|
{2: [1], 3: [2], 4: [3, 4]} will be inverted to |
10
|
|
|
{1: [1, 2], 2: [1, 3], 3: [1, 2, 4], 4: [2, 4], 5: [2]}. |
11
|
|
|
No order is preserved. |
12
|
|
|
|
13
|
|
|
:param dicts: The dictionaries to invert. |
14
|
|
|
:return: The inversed dictionary which merges all dictionaries into |
15
|
|
|
one. |
16
|
|
|
""" |
17
|
|
|
inverse = {} |
18
|
|
|
|
19
|
|
|
for dictionary in dicts: |
|
|
|
|
20
|
|
|
for key, value in dictionary.items(): |
21
|
|
|
if isinstance(value, Iterable): |
|
|
|
|
22
|
|
|
for item in value: |
23
|
|
|
add_pair_to_dict(item, key, inverse) |
24
|
|
|
else: |
25
|
|
|
add_pair_to_dict(value, key, inverse) |
26
|
|
|
|
27
|
|
|
return inverse |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
def add_pair_to_dict(key, value, dictionary): |
31
|
|
|
""" |
32
|
|
|
Add (key, value) pair to the dictionary. The value is added to a list of |
33
|
|
|
values for the key. |
34
|
|
|
""" |
35
|
|
|
if key in dictionary: |
36
|
|
|
dictionary[key].append(value) |
37
|
|
|
else: |
38
|
|
|
dictionary[key] = [value] |
39
|
|
|
|
40
|
|
|
|
41
|
|
|
def update_ordered_dict_key(dictionary, old_key, new_key): |
42
|
|
|
return OrderedDict(((new_key if k == old_key else k), v) |
|
|
|
|
43
|
|
|
for k, v in dictionary.items()) |
44
|
|
|
|