Click here to Skip to main content
16,019,876 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a pandas dataframe as follows, I want to convert it to a dictionary format with 2 keys as shown:



    	id	            name	                    energy      	   fibre	
    0	11005	4-Grain Flakes	                        1404	       	11.5	
    1	35146	4-Grain Flakes, Gluten Free	            1569			 6.1	
    2	32570	4-Grain Flakes, Riihikosken Vehnämylly	1443		    11.2	 

   
I am expecting the result to be of

     nutritionValues = {
      ('4-Grain Flakes', 'id'): 11005,
      ('4-Grain Flakes', 'energy'): 1404,
      ('4-Grain Flakes', 'fibre'):  11.5,
      ('4-Grain Flakes, Gluten Free', 'id'): 11005,
      ('4-Grain Flakes, Gluten Free', 'energy'): 1569,
      ('4-Grain Flakes, Gluten Free', 'fibre'):  6.1,
      ('4-Grain Flakes, Riihikosken Vehnämylly', 'id'): 32570,
      ('4-Grain Flakes, Riihikosken Vehnämylly', 'energy'): 1443,
      ('4-Grain Flakes, Riihikosken Vehnämylly', 'fibre'):  11.2}

    foods, fiber = multidict({
      '4-Grain Flakes': 11.5,
      '4-Grain Flakes, Gluten Free':   6.1,
      '4-Grain Flakes, Riihikosken Vehnämylly':   11.2})

How can I achieve this?


What I have tried:

df.set_index(["item1", "item2"]) # Columns for dict keys df_dict = df.to_dict("index") # Turn into dict It gives erro
Posted
Updated 18-Apr-19 3:41am
Comments
Richard MacCutchan 18-Apr-19 12:35pm    
I think you need to concatenate the two strings into a single string for the key.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900