0

I am trying to fetch some data from my backend to my frontend. However, in doing so, the data I receive looks something like:

[
    0: {"date": "2023-01-01", "id": "2023-01-01_0_GB", "product": "Snickers"},
    1: {"date": "2023-01-02", "id": "2023-01-02_0_GB", "product": "Bounty"},
    2: {"date": "2023-01-03", "id": "2023-01-03_0_GB", "product": "Twix"},
    ...
]

As you can see, the key is just numbers from 0 and up. But I would actually like the key do be the id of each dict.

From my backend I return the data by:

return DataResponse(
        df=df.to_dict(orient="records"),
    )

And it doesn't matter if I use reset_index() or not. If I do, that data will not be a part of the data received in the frontend, hence, I always use reset_index() so I have everything.

So yeah, how do I do that?

Denver Dang
  • 2,433
  • 3
  • 38
  • 68
  • Related answers can also be found [here](https://stackoverflow.com/a/70655118/17865804) and [here](https://stackoverflow.com/a/76044533/17865804) – Chris Jun 14 '23 at 09:08
  • Sorry @Chris, but that's a bad duplicate close - this is an issue related to using `set_index` to configure what is used as the dictionary key, not how to return a dataframe (which worked). – MatsLindh Jun 14 '23 at 09:16
  • @Chris Not an attack or anything, nor a blessing of the question. The asker does not necessarily know this because of their experience level, and when an answer that solves the issue has both been posted and accepted, marking it as a duplicate of an question that _isn't the same issue_ can be confusing for future readers. – MatsLindh Jun 14 '23 at 09:41

1 Answers1

3

As the docs state, orient=records returns a list of dicts. You probably want to return a dict of dicts:

import pandas as pd


df = pd.DataFrame({
    'a': [0, 1, 2],
    'b': [3, 4, 5],
    'id': ['id-1', 'id-2', 'id-3']
})

df.set_index('id').to_dict(orient='index')
# {'id-1': {'a': 0, 'b': 3}, 'id-2': {'a': 1, 'b': 4}, 'id-3': {'a': 2, 'b': 5}}
Plagon
  • 2,689
  • 1
  • 11
  • 23