ibarant
ibarant

Reputation: 276

How to create dictionary of dictionaries from a dataframe using python's pandas

I have the following dataframe directly from SQL query:

Question            tagID   Answer  
Primary purpose     62      Other  
Primary purpose     226     Learn how to use  
Primary purpose     227     Technical Support  
Primary purpose     292     Purchase  
Language            246     English  
Language            247     French   
Language            248     German  
Device              102     Desktop  
Device              103     Tablet  
Device              104     Mobile  

I need to get a dictionary like:

{Primary purpose: {62: 'Other', 226:'Learn how to use',227:'Technical Support',292:'Purchase' }, Language:{246:'English', 247:'French',248:'German'}, Device: {102: 'Desktop', 103:'Mobile', 104:'Tablet'}} 

I tried the following code, but it lists all values and labels:

    SS_valueLabelsSQL = {}
    for q in df['Question']:
       SS_valueLabelsSQL[q] = {}
       labels = df['Answer'].tolist()
       values = df['tagID'].tolist()
       SS_valueLabelsSQL[q] = dict(zip(values,labels))

Can somebody suggest a better solutions?

Upvotes: 0

Views: 551

Answers (1)

Stefan
Stefan

Reputation: 42875

You could use:

df.set_index('Question').groupby(level='Question').apply(lambda x: x.set_index('tagID').squeeze().to_dict()).to_dict()

to get:

{'Language': {248: 'German', 246: 'English', 247: 'French'}, 'Primary purpose': {226: 'Learn how to use', 227: 'Technical Support', 292: 'Purchase', 62: 'Other'}, 'Device': {104: 'Mobile', 102: 'Desktop', 103: 'Tablet'}}

Upvotes: 3

Related Questions