I have created a list of items with its associated key and values. but each time i invert the list it displays only the last item in the dictionary. Please help me check this code because the output is not what i expected. I actually wanted to invert the list so that each key is attached to a value. But it seems to work only for the last key and value in the dictionary.
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
for element in val:
if element not in inverse:
inverse[element] = [key]
else:
inverse[element].append(key)
return inverse
def main():
dict_1 = {"Protein_source_1": ['G.nuts', 'Eggs', 'Soya beans', 'Milk'], "Carbohydate_Source_2": ['Rice', 'Coco-yams', 'Yams'],"Vitamin_Source_3": ['potatoes', 'Vegetables', 'citrus furit'],"Fats_and_Oil_Source_4":['Butter', 'Coconut oil', 'fatty meats']}
print("\nOriginal Dictionary : ")
for k_1, v_1 in dict_1.items():
print('Key:', k_1, 'Value:', v_1)
i=invert_dict(dict_1)
print("\n This is the Inverted Dictionary : ")
for k_1, v_1 in i.items():
print('Key:', k_1, 'Value:', v_1)
if __name__ == "main":
main()
I expected it to display all the associated values and keys separately.
Original Dictionary :
Key: Protein_source_1 Value: ['G.nuts', 'Eggs', 'Soya beans', 'Milk']
Key: Carbohydate_Source_2 Value: ['Rice', 'Coco-yams', 'Yams']
Key: Vitamin_Source_3 Value: ['potatoes', 'Vegetables', 'citrus furit']
Key: Fats_and_Oil_Source_4 Value: ['Butter', 'Coconut oil', 'fatty meats']
This is the inverted dictionary :
Key: Butter Value: ['Fats_and_Oil_Source_4']
Key: Coconut oil Value: ['Fats_and_Oil_Source_4']
Key: fatty meats Value: ['Fats_and_Oil_Source_4', 'Fats_and_Oil_Source_4']