Select Page

How to Solve Python AttributeError: ‘str’ object has no attribute ‘keys’

by | Programming, Python, Tips

This error results from trying to call the dictionary method keys() on a string object. This error typically occurs when you have a JSON string instead of a Python dictionary.

You can solve this error by parsing the string to a Python dictionary using the json.dumps() method then call the keys() method on the dictionary. For example:

import json

my_str =  '{ "name":"Will", "age":45, "city":"Los Angeles"}'

my_dict = json.loads(my_str)

my_keys = my_dict.keys()

print(list(my_keys))

Otherwise, you can use a dictionary instead of a string.

This tutorial will go through the error in detail and how to solve it with code examples.


AttributeError: ‘str’ object has no attribute ‘keys’

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 “‘str’ object has no attribute ‘keys’” tells us that the string object does not have the attribute keys().

The keys() method belongs to the dict class and returns a view object that displays a list of all the keys in the specified dictionary.

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 keys() is not a str method by using the in operator to check if the method exists in the list object returned by dir().

string = "test"

attributes = dir(string)

print("keys" in attributes)
False

The membership operation returns False for the str object.

Let’s prove that keys() is a dict method by using the in operator:

my_dict =  { "name":"Jill", "age":20, "subject":"mathematics"}

print(type(my_dict))

attributes = dir(my_dict)

print("keys" in attributes)
<class 'dict'>
True

The membership operation returns True for the dict object.

Example

Let’s look at an example of how the error can occur.

my_str =  '{ "name":"Will", "age":45, "city":"Los Angeles"}'

my_keys = my_str.keys()

print(list(my_keys))

In the above code, we define a string representing a dictionary and then attempt to call the keys() method on the string. Let’s run the code, to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [17], in <cell line: 3>()
      1 my_str =  '{ "name":"Will", "age":45, "city":"Los Angeles"}'
----> 3 my_keys = my_str.keys()
      5 print(list(my_keys))

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

The error occurs because we are trying to call the keys() method on a string, which is an attribute of the dict class not the str class.

Solution #1: Use a Dictionary instead of a String

We can solve this error by using a Python dictionary instead of string.

We can use a dictionary by removing the quotation marks from the object. Let’s look at the revised code:

my_dict =  { "name":"Will", "age":45, "city":"Los Angeles"}

print(type(my_dict))

my_keys = my_dict.keys()

print(list(my_keys))

In the above code, we also renamed the object from my_str to my_dict.

Let’s run the code to see the result:

<class 'dict'>
['name', 'age', 'city']

We successfully retrieved the keys from the dict object and printed them to the console.

Solution #2: Parse the String to json.loads() to get a Python Dictionary

If we have a JSON string, we can use the json.loads() method to parse the string into a Python dictionary. Let’s look at the revised code:

import json

my_str =  '{ "name":"Will", "age":45, "city":"Los Angeles"}'

print(type(my_str))

my_dict = json.loads(my_str)

print(type(my_dict))

my_keys = my_dict.keys()

print(list(my_keys))

In the above code, we imported the json module in order to call the loads() method. Let’s run the code to see the result:

<class 'str'>
<class 'dict'>
['name', 'age', 'city']

We successfully parsed the string into a Python dictionary, which we verified using the type() method and retrieved the keys from the dictionary.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the article:

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!