Home > OS >  Question regarding converting one dictionary to csv fil
Question regarding converting one dictionary to csv fil

Time:07-29

I am new to Python and using pandas.

I am trying to convert a data in dictionary to csv file.

Here is the Dictionary

data_new = {'bedrooms': 2.0, 'bathrooms': 3.0, 'sqft_living': 1200,
            'sqft_lot': 5800, 'floors': 2.0,
            'waterfront': 1, 'view': 1, 'condition': 2, 'sqft_above': 1200,
            'sqft_basement': 20,
            'yr_built': 1925, 'yr_renovated': 2003, 'city': "Shoreline"}

And I use the below method to save and read the dictionary as csv file

 with open('test.csv', 'w') as f:
    for key in data_new:
        f.write("%s,%s\n" % (key, data_new[key]))
df1 = pd.read_csv("test.csv")
df1

And when I read df1 I get it in the below format enter image description here

but I want all rows to be columns so I used transpose function as below

enter image description here

However from the above output you see bathrooms is index 0 but I want index to start from bedrooms because with the below output if I try tdf1.info() I do not see bedroom data at all. enter image description here

Could you please guide me how I can fix this?

Regards Aravind Viswanathan

CodePudding user response:

I think it would be easier to just use pandas to both write and read your csv file. Does this satisfy what you're trying to do?

import pandas as pd

data_new = {'bedrooms': 2.0, 'bathrooms': 3.0, 'sqft_living': 1200,
            'sqft_lot': 5800, 'floors': 2.0,
            'waterfront': 1, 'view': 1, 'condition': 2, 'sqft_above': 1200,
            'sqft_basement': 20,
            'yr_built': 1925, 'yr_renovated': 2003, 'city': "Shoreline"}

df1 = pd.DataFrame.from_dict([data_new])
df1.to_csv('test.csv', index=None)  # index=None prevents index being added as column 1
df2 = pd.read_csv('test.csv')

print(df1)
print(df2)

Output:

   bedrooms  bathrooms  sqft_living  ...  yr_built  yr_renovated       city
0       2.0        3.0         1200  ...      1925          2003  Shoreline

[1 rows x 13 columns]

   bedrooms  bathrooms  sqft_living  ...  yr_built  yr_renovated       city
0       2.0        3.0         1200  ...      1925          2003  Shoreline
[1 rows x 13 columns]

Identical.

  • Related