1
Name = [list(['Amy', 'A', 'Angu']),
          list(['Jon', 'Johnson']),
          list(['Bob', 'Barker'])]

Other =  [list(['Amy', 'Any', 'Anguish']),
        list(['Jon', 'Jan']),
        list(['Baker', 'barker'])]

import pandas as pd
df = pd.DataFrame({'Other' : Other,  
                  'ID': ['E123','E456','E789'], 
                  'Other_ID': ['A123','A456','A789'],
                  'Name' : Name,

                 })

    ID              Name    Other               Other_ID
0   E123    [Amy, A, Angu]  [Amy, Any, Anguish] A123
1   E456    [Jon, Johnson]  [Jon, Jan]          A456
2   E789    [Bob, Barker]   [Baker, barker]     A789

I have the df as seen above. I want to make columns ID, Name and Other into a dictionary with they key being ID. I tried this according to python pandas dataframe columns convert to dict key and value

todict = dict(zip(df.ID, df.Name))

Which is close to what I want

{'E123': ['Amy', 'A', 'Angu'],
 'E456': ['Jon', 'Johnson'],
 'E789': ['Bob', 'Barker']}

But I would like to get this output that includes values from Other column

{'E123': ['Amy', 'A', 'Angu','Amy', 'Any','Anguish'],
 'E456': ['Jon', 'Johnson','Jon','Jan'],
'E789':  ['Bob', 'Barker','Baker','barker']
}

And If I put the third column Other it gives me errors

todict = dict(zip(df.ID, df.Name, df.Other))

How do I get the output I want?

1 Answers1

1

Why not just combine the Name and Other column before creating a dict of the Name column.

df['Name'] = df['Name'] + df['Other']

dict(zip(df.ID, df.Name))

Gives

{'E123': ['Amy', 'A', 'Angu', 'Amy', 'Any', 'Anguish'],
 'E456': ['Jon', 'Johnson', 'Jon', 'Jan'],
 'E789': ['Bob', 'Barker', 'Baker', 'barker']}
Chris
  • 1,287
  • 12
  • 31