Last modified: Dec 12, 2025 By Alexander Williams
Fix Python AttributeError 'str' object has no attribute 'items'
Python errors can stop your code. One common error is AttributeError.
This error says a string object has no attribute 'items'. It is confusing for beginners.
This guide explains why it happens. You will learn how to fix it for good.
Understanding the Error Message
The error message is very specific. It tells you the exact problem.
AttributeError: 'str' object has no attribute 'items'.
This means you tried to call .items() on a string. The .items() method is for dictionaries.
Strings do not have this method. Python tells you this with the error.
You must check your variable's data type. It is likely a string, not a dict.
Why .items() Works Only on Dictionaries
In Python, each data type has specific methods. These are called attributes.
The .items() method belongs to the dictionary type. It returns key-value pairs.
Strings have different methods. For example, .lower() or .split().
Calling a dictionary method on a string causes this AttributeError.
This is a common type confusion error. Similar errors include 'str' object has no attribute 'keys'.
Common Causes and Examples
Let's look at code that causes the error. Understanding the cause is the first step.
Cause 1: Variable is Actually a String
You might think a variable is a dictionary. But it is a string.
This often happens with data from files or user input. It comes as text.
# Example 1: JSON string not parsed
import json
json_string = '{"name": "Alice", "age": 30}'
print(type(json_string)) # It's a str, not a dict
# This will cause the error
for key, value in json_string.items(): # AttributeError here
print(key, value)
Output:
<class 'str'>
Traceback (most recent call last):
File "script.py", line 7, in <module>
for key, value in json_string.items():
AttributeError: 'str' object has no attribute 'items'
Cause 2: Function Returns a String Instead of a Dict
A function may return different types. You might expect a dictionary.
If it returns a string, calling .items() will fail.
# Example 2: Function returns a string representation
def get_data():
# Simulating a function that returns a string
return "{'product': 'book', 'price': 20}"
data = get_data()
print(f"Type of data: {type(data)}")
# Error occurs here
items_list = data.items() # AttributeError
Cause 3: Incorrect Variable Assignment
You may accidentally overwrite a dictionary. You might assign a string to it.
Later code tries to use .items() on the new string value.
# Example 3: Variable reassigned to a string
user_profile = {"username": "john_doe", "active": True}
# Later in the code, accidentally reassign
user_profile = "admin_user"
# This line will now fail
print(user_profile.items()) # AttributeError
How to Diagnose the Problem
Before fixing, confirm the issue. Use these simple debugging steps.
First, check the type of your variable. Use the type() function.
Second, print the variable's value. See if it looks like a dict or a string.
# Debugging code
problem_variable = some_function()
print(f"Type: {type(problem_variable)}")
print(f"Value: {problem_variable}")
print(f"Is it a dict? {isinstance(problem_variable, dict)}")
This tells you if your variable is a string. You can then find where it became one.
Similar type-checking helps with errors like 'list' object has no attribute 'items'.
Step-by-Step Solutions to Fix the Error
Here are proven solutions. Choose the one that fits your situation.
Solution 1: Parse JSON Strings into Dictionaries
If your string is JSON, parse it. Use the json.loads() function.
This converts a JSON-formatted string into a Python dictionary.
# Fix for JSON strings
import json
json_string = '{"name": "Alice", "age": 30}'
print(f"Before: {type(json_string)}")
# Convert string to dictionary
data_dict = json.loads(json_string)
print(f"After: {type(data_dict)}")
# Now .items() works correctly
for key, value in data_dict.items():
print(f"{key}: {value}")
Output:
Before: <class 'str'>
After: <class 'dict'>
name: Alice
age: 30
Solution 2: Use ast.literal_eval for Python Literals
Your string might be a Python literal. Like a dictionary printed as a string.
Use ast.literal_eval() to convert it safely. It evaluates Python literals.
# Fix using ast.literal_eval
import ast
string_repr = "{'product': 'book', 'price': 20}"
print(f"String: {string_repr}, Type: {type(string_repr)}")
# Safely evaluate the string to a dict
real_dict = ast.literal_eval(string_repr)
print(f"Dict: {real_dict}, Type: {type(real_dict)}")
# Now you can use .items()
print(list(real_dict.items()))
Output:
String: {'product': 'book', 'price': 20}, Type: <class 'str'>
Dict: {'product': 'book', 'price': 20}, Type: <class 'dict'>
[('product', 'book'), ('price', 20)]
Solution 3: Ensure Function Returns a Dictionary
Fix the source. Make sure your function returns a dict, not a string.
Review the function's logic. Remove any str() conversions that cause the issue.
# Original problematic function
def get_config():
config = {"theme": "dark", "version": 2}
# Mistakenly returning a string representation
return str(config) # This is the bug!
# Fixed function
def get_config_fixed():
config = {"theme": "dark", "version": 2}
return config # Return the dict itself
data = get_config_fixed()
print(data.items()) # Works perfectly
Solution 4: Add Type Checking and Handling
Make your code robust. Check the type before calling .items().
Use a conditional statement. Or use a try-except block to handle the error.
# Robust code with type checking
def process_data(data):
if isinstance(data, dict):
# It's a dict, use .items()
for k, v in data.items():
print(k, v)
elif isinstance(data, str):
# It's a string, try to convert it
print("Received a string. Attempting conversion...")
try:
data_dict = json.loads(data)
process_data(data_dict) # Call recursively with dict
except json.JSONDecodeError:
print("Error: String is not valid JSON.")
else:
print(f"Unsupported type: {type(data)}")
# Test it
process_data('{"key": "value"}')
process_data({"key": "value"})
Best Practices to Avoid This Error
Follow these tips. They will prevent this error in future projects.
First, know your data types. Always be aware of what type a variable holds.
Second, validate external data. Files, APIs, and user input often give strings.
Third, use type hints. They make your code's expected types clear.
Fourth, write unit tests. Tests can catch type mismatches early.
These practices also help avoid related errors like 'dict' object has no attribute 'split'.
Conclusion
The AttributeError about 'str' and 'items' is a type error. You called a dictionary method on a string.
The fix is to ensure you have a dictionary. Convert strings using json.loads() or ast.literal_eval().
Always check variable types with type() or isinstance(). Debugging is key.
Understanding this error makes you a better Python programmer. You now know how to fix it quickly.
Keep this guide handy. You can solve this error and similar ones with confidence.