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

AttributeError: ‘str’ object has no attribute ‘keys’ error occurs when you try to use a keys() method or attribute on a string object, but it does not exist.

When an error occurs?

Here are two scenarios where the AttributeError: ‘str’ object has no attribute ‘keys’ error occurs.

  1. Treating a string as a dictionary
  2. Converting a dictionary to a string and then trying to access its keys

Scenario 1: Treating a string as a dictionary

main_str = "Michael Gambon is DumbleDore! RIP"

print(main_str.keys())

Output

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

Scenario 2: Convert a dictionary to a string and then access its keys

main_dict = {"albus": "Michael", "dumbledore": "Richard"}

main_str = str(main_dict)

print(main_str.keys())

Output

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

How to fix the error?

Here are two ways to fix the error:

  1. Using the type() method
  2. Using the json.loads() method

Diagram of AttributeError - 'str' object has no attribute 'keys'

Solution 1: Using the type() method

You can use the type() function to check if a variable is a dictionary before calling the keys() method. 

main_dict = {"albus": "Michael", "dumbledore": "Richard"}
main_str = "Partis Temporas"

if type(main_dict) == dict:
  print(main_dict.keys())
else:
  print("Not a dictionary")

if type(main_str) == dict:
  print(main_str.keys())
else:
  print("Not a dictionary")

Output

dict_keys(['albus', 'dumbledore'])
Not a dictionary

Solution 2: Use the json.loads() method

You can use the json.loads() function to ensure you are creating a dictionary object in the first place.

import json

main_str = '{"albus": "Michael", "dumbledore": "Richard"}'

main_dict = json.loads(main_str)

print(main_dict.keys())

Output

dict_keys(['albus', 'dumbledore'])

We can now safely use the keys() method on the main_dict variable without raising an error.

If you are unsure whether a variable is a dictionary or a string, the type() method (or isinstance()) is the way to go.

If you are sure that you have a JSON-formatted string and you want to convert it to a dictionary, then json.loads() is appropriate.

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.