简体   繁体   中英

How to convert two columns values into a key-value pair dictionary?

How to convert values from the columns from the DataFrame below to a key-value pair dictionary like {"a": 29, "b": 1042, "c": 2928, "d": 4492}

    event_type  count
0   a           29
1   b           1042
2   c           2928
3   d           4492

Create Series and convert to dict :

d = df.set_index('event_type')['count'].to_dict()
print (d)
{'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}

One way is using zip :

dict(zip(*df.values.T))
# {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}

If the dataframe contains more columns:

dict(zip(df['event_type'], df['count']))
# {'a': 29, 'b': 1042, 'c': 2928, 'd': 4492}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM