Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a dictionary to another one [duplicate]

I have a dictionary, the keys are integer values and the values are a list of strings. I want to make it vice versa, the string become key and integers become values. Like:

first design:

{1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}

second design:

{"a": [1,2,3,6], "b":[2,4], "cd":[4,6]}

any clue? Thanks

like image 383
B bonita Avatar asked Sep 13 '25 07:09

B bonita


2 Answers

A simple approach would be to create a defaultdict that provides an empty list for new keys, and then for each list in your current dict, create a key for each element and append the original dict key to the new list:

from collections import defaultdict

orig = {1: ['a'], 2: ['a', 'b'], 3: ['a'], 4: ['b', 'cd'], 6: ['a', 'cd']}
d = defaultdict(list)

for k, v in orig.items():
    for string in v:
        d[string].append(k)

# d = {'a': [1, 2, 3, 6], 'b': [2, 4], 'cd': [4, 6]}
like image 200
mattjegan Avatar answered Sep 15 '25 21:09

mattjegan


For the love of one-liners (note: heavily inefficient!):

d2 = {val: [key for key in d if val in d[key]] for lst in d.itervalues() for val in lst}
like image 39
perigon Avatar answered Sep 15 '25 21:09

perigon