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.
- Treating a string as a dictionary
- 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:
- Using the type() method
- Using the json.loads() method
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!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.