Home > OS >  How to convert this specific format of dict to CSV in Python
How to convert this specific format of dict to CSV in Python

Time:12-09

I have a dictionary of persons uniquely identified by an id. Now I need to convert the dict to csv and write it to a path. However I need a more efficient solution because I don't think my method will work well with large dataset.

Python dict

names = {
  0: {
    "id": 0,
    "name": "William",
    "age": 19
  },
  1: {
    "id": 1,
    "name": "John",
    "age": 29
  },
  2: {
    "id": 2,
    "name": "Tim",
    "age": 42
  }
}

Expected output

id,name,age
0,William,19
1,John,29
2,Tim,42

My attempt:

data = []

for key in names:
  person = names[key]

  data.append({
    "id": person["id"],
    "name": person["name"],
    "age": person["age"]
  })

df = pd.json_normalize(data)
df.to_csv('./persons.csv', index=False, na_rep='\"')

Do you have a more efficient way of doing this? I cannot change my initial dict structure.

CodePudding user response:

Try with from_dict

pd.DataFrame.from_dict(names,'index')
Out[197]: 
   id     name  age
0   0  William   19
1   1     John   29
2   2      Tim   42

CodePudding user response:

My other attempt

df = pd.DataFrame.from_dict(products, orient='index').reset_index(drop=True)
  • Related