4

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
B bonita
  • 171
  • 2
  • 5

6 Answers6

3

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]}
mattjegan
  • 2,724
  • 1
  • 26
  • 37
2

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}
perigon
  • 2,160
  • 11
  • 16
2

Code

first_map = {1: ["a"], 2: ["a", "b"], 3: ["a"], 4: ["b", "cd"], 6: ["a", "cd"]}
second_map = {}
for key, value in first_map.items():
    for i in value:
        if i in second_map:
            second_map[i].append(key)
        else:
            second_map[i] = [key]
print(second_map)
rsu8
  • 491
  • 4
  • 10
1
z = {1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}
d = dict()

for k, v in z.iteritems():
    for i in v: 
        if i in d: 
            d[i].append(k)
        else:   
            d[i] = [k]

Using iteritems() over items() is a little better because the former creates a generator in Python 2.

Cory Madden
  • 5,026
  • 24
  • 37
1
dict1= {1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}
dict2= {}
for key, value in dict1.items():
   for val in value:
       if val in dict2:
           dict2[val].append(key)
           dict2[val]= list(set(dict2[val]))
       else:
           dict2[val]= [key]
Himanshu
  • 1,002
  • 9
  • 22
1
from collections import defaultdict

second_dict = defaultdict(list)

for key, value in first_dict.items():

    for item in value:

        second_dict[item].append(key)
stamaimer
  • 6,227
  • 5
  • 34
  • 55