Set-up
I have a large dictionary with unique keys, unique values and non-unique values in lists.
Dictionary looks like,
d = {'a': ['1','2','3'],'b': ['1'],'c': ['1','3']}
Problem
I'd like to swap the keys and values such that,
d_inverse = {'1': ['a', 'b', 'c'], '2': ['a'],'3': ['a', 'c']}
I've found the following answers about swapping keys and values,
and about swapping keys with values in lists,
the last answer comes close, but doesn't manage non-unique values in lists.
That is,
{k: oldk for oldk, oldv in d.items() for k in oldv}
produces
{'1': 'c', '2': 'a', '3': 'c'}
How do I account for the non-unique values and don't lose information?
int
andstring
values in the lists ind
, so your output isn't quite right (it should have both'1'
and1
keys). – match