Sidharth Sekhar
Sidharth Sekhar

Reputation: 11

Python dictionary, value-key mapping

I have a python dictionary that looks like this {3:[2,3,4,5],4:[3,6,7,8]}.
I need to map the values in dictionary to the keys. i.e {2:[3],3:[3,4],4:[3],5:[3],6:[4],7:[4],8:[4]}.

How can I do that?

Upvotes: 0

Views: 45

Answers (1)

user2390182
user2390182

Reputation: 73498

Loop through the dict and through each value list to build the new structure. You can use dict.setdefault (or a collections.defaultdict) to save yourself some boilerplate code:

data = {3: [2, 3, 4, 5], 4: [3, 6, 7, 8]}
rev = {}

for k, lst in data.items():
    for val in lst:
        rev.setdefault(val, []).append(k)
rev
# {2: [3], 3: [3, 4], 4: [3], 5: [3], 6: [4], 7: [4], 8: [4]}

or

from collections import defaultdict

rev = defaultdict(list)
for k, lst in data.items():
    for val in lst:
        rev[val].append(k)

Upvotes: 1

Related Questions