python pandas dataframe columns convert to dict key and value

186,190

Answering @Jessie Marks question, on how to use this dict(zip(***)) approach if you want to use multiple columns as keys / values, the answer is to zip the zips; e.g.:

dict(zip(df['key'], zip(df["value col 1"], df_['value col 1'])))

or if you wish to use multiple columns as keys:

dict(zip(zip(df['key 1'], df['key 2']), zip(df["value col 1"], df_['value col 1'])))

this worked for me on pandas v1.1.5 ; python 3.6.13

PS. sorry i do not respond directly under @Jessie Marks question, its new account and I cannot do that yet.

Share:
186,190
perigee
Author by

perigee

Updated on January 14, 2022

Comments

  • perigee
    perigee over 2 years

    I have a pandas data frame with multiple columns and I would like to construct a dict from two columns: one as the dict's keys and the other as the dict's values. How can I do that?

    Dataframe:

               area  count
    co tp
    DE Lake      10      7
    Forest       20      5
    FR Lake      30      2
    Forest       40      3
    

    I need to define area as key, count as value in dict. Thank you in advance.