1

I have a dictionary with multiple values in each Keys. I want to reverse the dictionary so that all Values present in different Keys can be stored in Value:Keys pair (keeping in mind that a value can exist over multiple keys).

Sample Data :

{
  "1A": [
    "mathematics"
  ],
  "1B": [
    "problem-solving",
    "model"
  ],
  "1C": [
    "basic",
    "model"
  ]
}

OUTPUT :

{
  "mathematics": [
    "1A"
  ],
  "problem-solving": [
    "1B"
  ],
  "model" : [
    "1B" ,
    "1C"
  ],
  "basic": [
    "1C",
  ]
}

As you see, MODEL has 2 values 1B & 1C now.

I have tried different approaches but all seem to assume that Key:Values have to be unique. All the below approaches fail with above scenario.

Approach-1 :

my_dict2 = {y:x for x,y in instr_dict.iteritems()}
instr_json =  json.dumps(new_dict)
print(instr_json)

Approach-2 :

my_dict2 = dict((y,x) for x,y in instr_dict.items())
instr_json =  json.dumps(new_dict)
print(instr_json)

Approach-3 :

b = dict()
for k, v in instr_dict.items(): # a.iteritems() in python 2
    b[v] = k
    del instr_dict[k]
a = b
print(a)

Can someone help with the right approach to solve this ?

Shankar Pandey
  • 451
  • 1
  • 4
  • 22

1 Answers1

3

Just do it by looping over the dictionary. If the new key is in the dictionary, append the value, else create a list with that value.

Here is the working code.

newDict = {}
for key,value in instr_dict.items():
    for val in value:
        if val in newDict:
            newDict[val].append(key)
        else:
            newDict[val] = [key]

print(newDict)
hsnsd
  • 1,728
  • 12
  • 30