0

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']
Grismar
  • 27,561
  • 4
  • 31
  • 54
Skibo
  • 11
  • 1
  • 2
    You loop `for key in d:`, but only to overwrite `val` several times, you then only use the value that was last assigned to `val`. Did you mean to indent the second loop? – Grismar Mar 17 '23 at 04:16
  • `k2v = lambda d: {v:k for k,vs in d.items() for v in vs}` – OneMadGypsy Mar 17 '23 at 04:50

1 Answers1

0

You have to nest your iterations, so you can go over all the keys, and all the values for each key.

This is the basic idea, you can adapt that to your code:

inv = dict()
for k in dict_1:
    for v in dict_1[k]:
        if v not in inv:
            inv[v] = []
        if k not in inv[v]:
            inv[v] += [k]
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36