Skip to content
Advertisement

Switch pandas data frame to dictionary

I have a pandas data frame of the following shape:

MNK Monkey
CT Cat
GNNPG Guinnea Pig

And I want to switch it into such dictionary:

{‘MNK’:’Monkey’,’CT’:’Cat’,’GNNPG’:’Guinnea Pig’}

Is there a way of doing such transformation (without iterating on rows) ?

Advertisement

Answer

Calling your DataFrame as df and columns code and `animal, you can declare a dictionary iterating over it. That is:

your_dict = {c: a for c, a in zip(df.code, df.animal)}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement