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 ?