0

I need to convert a dictionary into a CSV. I have the following code.

dict01 = {
            "A": ["1", "2", "3", "4"],
            "B": [2.0, 3.0, 2.0, 5.0]
        }

df01 = pd.DataFrame([dict01])

df01.to_csv('csv01.csv')

The resulting CSV looks like this:

A B
["1", "2", "3", "4"] [2.0, 3.0, 2.0, 5.0]

But I need my resulting CSV to look like this:

A B
1 2.0
2 3.0
3 4.0
4 5.0
mirkap
  • 7
  • 1
  • 4
  • 1
    Welcome to Stack Overflow. Did you check that the `DataFrame` itself is correct, before attempting to create the CSV file? I think you will find it does not contain what you expect it to. There is a simple reason for this: `pd.DataFrame([dict01])` does not make sense, as you are creating a one-element list out of `dict01` and then trying to create a `DataFrame` from *that*. If you look at the examples in the documentation, you will see how this doesn't match. – Karl Knechtel Nov 09 '21 at 16:00
  • Worth learning to do this without pandas (which is overkill in this scenario, and many others here on Stack Overflow). You can use native file i/o or the csv module. – jarmod Nov 09 '21 at 16:03

1 Answers1

1

You can fix this by removing the list on this line:

df01 = pd.DataFrame([dict01])

So the fixed code looks like this:

import pandas as pd

dict01 = {
            "A": ["1", "2", "3", "4"],
            "B": [2.0, 3.0, 2.0, 5.0]
        }

df01 = pd.DataFrame(dict01)

df01.to_csv('csv01.csv')
Nick ODell
  • 15,465
  • 3
  • 32
  • 66