Attributeerror: ‘str’ object has no attribute ‘items’ [SOLVED]

In this article, we will deal with the error Attributeerror: ‘str’ object has no attribute ‘items’. We will look for solutions and discuss what is this error all about.

Let’s start!

What is Attributeerror: ‘str’ object has no attribute ‘items’ ?

This error AttributeError: ‘str’ object has no attribute ‘items’ of python occurs when we call the item() method on a string instead of a dictionary.

In order to fix this error we need to parse the string if we have the JSON string or correct the assignment and call items() on a dict.

Here is how this error occurs:

my_dict = '{"itsc": "It Sourcecode", "age": 7}'

print(my_dict.items())

If we run the code it will give the following output:

AttributeError: 'str' object has no attribute 'items'

How to fix Attributeerror: ‘str’ object has no attribute ‘items’

To fix this error here are the following solutions:

Use the json.loads() method

Use the json.loads() method if having JSON string when we parse it into a native python dictionary. Additionally, we use this json.loads() method to parse string before calling the item() method.

Here is the example code:

import json

my_dict = '{"itsc": "IT Itsourcecode", "age": 7}'

parsed = json.loads(my_dict)

print(parsed.items())

Output:

dict_items([('itsc', 'IT Itsourcecode'), ('age', 7)])

Use the isinstance function

When we want to check first the dictionary prior to calling the times() method, we are going to use isinstance function.

This will return TRUE if our passed-in object is an instance or a subclass of the passed-in class.

Here is how it works:

my_dict = {"itsc": "IT SOURCECODE", "age": 20}


if isinstance(my_dict, dict):
    print(my_dict.items())

Output:

dict_items([('itsc', 'IT SOURCECODE'), ('age', 20)])

headers dictionary to JSON

Take note when we use headers keyword it should be a python dictionary and not a JSON string.

Here is the example code:

import requests


def make_request():
    res = requests.post(
        'https://reqres.in/api/users',
        data={'itsc': 'IT Sourcecode', 'provide': 'code'},
        headers={'Accept': 'application/json',
                 'Content-Type': 'application/json'}
    )

    print(res.json())

make_request()

json.dumps() method

When we convert JSON string, keep in mind that we shouldn’t call the json.dumps() method in a dictionary. Wherein, json.dumps method converts a Python object to a JSON formatted string.

import json

my_dict = {"itsc": "IT SOURCECODE", "age": 20}
print(type(my_dict)) 

# json.dumps() converts a Python object to JSON string
json_str = json.dumps(my_dict)
print(type(json_str))  # <class 'str'>

Output:

<class 'dict'>
<class 'str'>

Use the json.loads() method

We use json.loads() if we have JSON string and if we need to parse it into native python dictionary.

import json

json_str = r'{"itsc": "IT SOURCECODE", "age": 20}'

my_dict = json.loads(json_str)

print(type(my_dict))  # <class 'dict'>

Output:

<class 'dict'>

JSONDecodeError is raised

When data is not valid as JSON string, this JSONDecodeError will occur. The best way to debug it is to print(dir(your_object)) to see what attributes a string has.

Certainly, when we pass to the dir() function, this will return the list of class attributes name, and recursively of the attributes of its bases.

Here is an example:

my_string = 'itsourcecode.com'

# [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format',
#  'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
#  'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
#  'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex',
#  'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
#  'title', 'translate', 'upper', 'zfill']
print(dir(my_string))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Note: If you attempt to access any attribute that is not in this list, you would get the "AttributeError: str object has no attribute error".

Conclusion

In conclusion, the Python error Attributeerror: 'str' object has no attribute 'items' can be easily solved by using the json.loads() methods.

By following the guide above, which works best for you there’s no doubt that you’ll be able to resolve this error quickly and without a hassle.

If you are finding solutions to some errors you might encounter we also have  Typeerror: can’t compare offset-naive and offset-aware datetimes.

Leave a Comment