Select Page

How to Solve Python AttributeError: ‘dict’ object has no attribute ‘read’

by | Programming, Python, Tips

This error results from trying to call the File method read() on a dictionary object. This error typically occurs when passing a Python dictionary to the json.load() method to convert it to a JSON string.

You can solve the error by using the json.dumps() method to convert the dictionary to a JSON formatted string. For example,

import json

example_dict = {"fruit":"apple", "price":0.99}

json_str = json.dumps(example_dict)

This tutorial will go through how to solve the error with code examples.


AttributeError: ‘dict’ object has no attribute ‘read’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘dict’ object has no attribute ‘read’” tells us that the dictionary object does not have the attribute read().

The read() method belongs to the _io.TextIOWrapper class and returns the file content.

We can check an object’s attributes by using the built-in dir() method. The dir() method returns all the properties and methods of the specified object as a list.

Let’s verify that read() is not a dict method by using the in operator to check if the method exists in the list object returned by dir().

example_dict = {"fruit":"apple", "price":0.99}

attributes = dir(example_dict)

print("read" in attributes)
False

The membership operation returns False for the dict object.

Let’s prove that read() is an _io.TextIOWrapper method by using the in operator. We will open the file pizza.json, which contains the following data:

[
        {"margherita":7.99},
        {"pepperoni":9.99},
        {"four cheeses":10.99}
]
file_name = 'pizza.json'
with open(file_name, 'r') as f:
    print(type(f))
    attributes = dir(f)
    print('read' in attributes)
<class '_io.TextIOWrapper'>
True

The membership operation returns True for the _io.TextIOWrapper object.

Example

Let’s look at an example of trying to convert a Python dictionary into a JSON string.

import json

particle_dict = {"name":"muon", "mass": 105.7, "charge":-1, "spin":0.5}

json_str = json.load(particle_dict)

print(json_str)

In the above code, we import the json module and define a dictionary containing information about the muon. Next, we pass the dictionary to the json.load() method call and print the result returned from the call to the console. Let’s run the code to see the result:

AttributeError: 'dict' object has no attribute 'read'

The error occurs because we are trying to convert a Python object to a JSON string using the json.load() method. We use the json.load() method to deserialize a file to a Python object.

Solution #1: Use json.dumps() to convert dictionary to JSON string

We can convert a Python object to a JSON string using the json.dumps() method. Let’s look at the revised code:

import json

particle_dict = {"name":"muon", "mass": 105.7, "charge":-1, "spin":0.5}

json_str = json.dumps(particle_dict)

print(json_str)

Let’s run the code to get the result:

{"name": "muon", "mass": 105.7, "charge": -1, "spin": 0.5}

We successfully converted the particle dictionary to a JSON string using the json.dumps() method.

Solution #2: Use json.loads() to parse a JSON string into a native Python object

We can use the json.loads() method to parse a JSON string into a Python object. This approach is only suitable if we are starting with a JSON string. Let’s look at the revised code:

import json

json_str = '{"name":"muon", "mass": 105.7, "charge":-1, "spin":0.5}'

particle_dict = json.loads(json_str)

print(particle_dict)

print(type(particle_dict))

We can use the json.loads() method to parse a JSON string into a Python object. This approach is only suitable if we are starting with a JSON string. Let’s look at the revised code:

{'name': 'muon', 'mass': 105.7, 'charge': -1, 'spin': 0.5}
<class 'dict'>

We successfully parsed the JSON string and converted it to a Python dictionary.

Correct Use of json.load

The json.load() method is for deserializing a file object containing JSON data to a Python object.

Let’s look at a file containing information about the muon particle.

{"name": "muon", "mass": 105.7, "charge": -1, "spin": 0.5}

We will name the file “muon.json“.

Next, we will use a context manager to create a file object and then pass it to the json.load() method call and print the resulting Python dictionary to the console.

import json

file_name = 'muon.json'

with open(file_name, 'r') as f:

    json_data = json.load(f)

    print(json_data)

    print(type(json_data))

Let’s run the code to get the result:

{'name': 'muon', 'mass': 105.7, 'charge': -1, 'spin': 0.5}
<class 'dict'>

We successfully deserialized the File object into a Python dictionary.

Summary

Congratulations on reading to the end of this tutorial!

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!