Attributeerror: ‘dict’ object has no attribute ‘to_csv’

The error AttributeError: ‘dict’ object has no attribute ‘to_csv’ occurs when you try to use the to_csv() method on a dictionary object. The to_csv() method is not a built-in method for dictionaries, hence the error is thrown.

The to_csv() method is typically used to convert a pandas DataFrame object into a CSV (Comma Separated Values) file. It is not directly applicable to dictionaries. To resolve the error, you need to convert your dictionary into a DataFrame before using the to_csv() method.

Here’s an example that illustrates how to convert a dictionary into a pandas DataFrame and then save it as a CSV file:

// Import required libraries
import pandas as pd

# Example dictionary
data = {
  'Name': ['John', 'Emily', 'Ryan'],
  'Age': [25, 30, 28],
  'City': ['New York', 'London', 'Sydney']
}

# Convert dictionary to DataFrame
df = pd.DataFrame(data)

# Save DataFrame as CSV file
df.to_csv('output.csv', index=False)

In the above example, we first import the required pandas library. Then, we define a dictionary data that contains three keys (Name, Age, City) and their corresponding values. Next, we convert the dictionary into a DataFrame using the DataFrame() constructor provided by pandas. Finally, we save the DataFrame as a CSV file named output.csv using the to_csv() method.

By following these steps, you can avoid the AttributeError: ‘dict’ object has no attribute ‘to_csv’ error and successfully save a dictionary as a CSV file.

Similar post

Leave a comment