-3

I have following dataframe in pandas:

               US46434V7617  US3160928731  US4642865251
2021-07-20     13.741297     53.793367    104.151499

How can I convert this to a dict with as keys the columns and as values the values of the columns. For example:

[{'US46434V7617': 13.741297048948578, 'US3160928731': 53.7933674972021, 'US4642865251': 104.15149908700006}]
sg_sg94
  • 2,248
  • 4
  • 28
  • 56
  • What about the index . . . are you looking for `df.to_dict(orient='index')`? or do you want `orient='records'` – It_is_Chris Jul 21 '21 at 13:08
  • 1
    Prior to your edit, note that what you wanted to obtain was a [set](https://www.w3schools.com/python/python_sets.asp) of 3 [dictionaries](https://www.w3schools.com/python/python_dictionaries.asp). Such object does not exist in python since dictionaries are [unhashable](https://stackoverflow.com/questions/1957396/why-dict-objects-are-unhashable-in-python). – keepAlive Jul 21 '21 at 13:13

1 Answers1

2

You can use df.to_dict with orient='records':

df.to_dict(orient='records')

This will give you a list of dictionaries, one for each row. By the way, the structure you provided in the question is not valid, it must be a list of dictionaries or a dictionary with key:value pairs

IoaTzimas
  • 10,538
  • 2
  • 13
  • 30