Str object has no attribute питон

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

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)

The membership operation returns False for the str object.

Читайте также:  Nginx path index html

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)

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 () 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:

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:

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!

Share this:

Источник

Str object has no attribute питон

Last updated: Jan 28, 2023
Reading time · 5 min

banner

# AttributeError: ‘str’ object has no attribute ‘get’ (Python)

The Python «AttributeError: ‘str’ object has no attribute ‘get'» occurs when we try to call the get() method on a string instead of a dictionary.

To solve the error, make sure the value is of type dict before calling the get() method on it.

attributeerror str object has no attribute get

Here is an example of how the error occurs.

Copied!
my_str = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'get' print(my_str.get('name'))

We tried to call the get() method on a string instead of a dictionary and got the error.

# Make sure to call get() on a dictionary

If you are trying to get the value of a specific key in a dictionary, make sure the value you are calling get() on is a dict.

Copied!
my_dict = 'name': 'Alice', 'age': 30> print(my_dict.get('name')) # 👉️ 'Alice' print(my_dict.get('age')) # 👉️ 30

only call get method on dictionaries

If you need to check if the variable is a dictionary before calling get() , use the isinstance() method.

Copied!
my_dict = 'name': 'Alice', 'age': 30> if isinstance(my_dict, dict): print(my_dict.get('name')) # 👉️ 'Alice' print(my_dict.get('age')) # 👉️ 30 else: print('The value is NOT a dictionary')

check if value is dictionary before calling get

The if block runs only if the variable stores a dictionary.

Otherwise, the else block runs.

# Reassigning the variable by mistake

Make sure the variable doesn’t get reassigned to a string somewhere in your code.

Copied!
my_dict = 'name': 'Alice', 'age': 30> # 👇️ reassigned to string by mistake my_dict = 'hello world' # ⛔️ AttributeError: 'str' object has no attribute 'get' print(my_dict.get('name'))

We initially set the my_dict variable to a dictionary, but later reassigned it to a string which caused the error.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

Name Description
key The key for which to return the value
default The default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .

# Using the hasattr() method to check if the value has a get attribute

If you need to handle a scenario where the value is possibly not a dict, use the hasattr() method.

Copied!
my_dict = 'name': 'Alice', 'age': 30> if hasattr(my_dict, 'get'): print(my_dict.get('name')) # 👉️ "Alice" else: print('Value is not a dict')

using hasattr method to check for get attribute

The hasattr function takes the following 2 parameters:

Name Description
object The object we want to test for the existence of the attribute
name The name of the attribute to check for in the object

The hasattr() function returns True if the string is the name of one of the object’s attributes, otherwise False is returned.

Using the hasattr function would handle the error if the get attribute doesn’t exist on the object, however, you still have to figure out where the variable gets assigned a string in your code.

# Accessing a string at a specific index

If you are trying to access a string at a specific index, use square brackets.

Copied!
my_str = 'hello world' try: print(my_str[100]) except IndexError: print('Index 100 is not present in string') # 👉️ this runs

accessing string at specific index

Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(a_string) — 1 .

We used a try/except statement to handle the scenario where the index we are trying to access is out of bounds.

# Getting a substring of a string with string slicing

If you need to get a substring from a string, use string slicing.

Copied!
my_str = 'hello world' # 👇️ from index 0 (inclusive) to 5 (exclusive) print(my_str[0:5]) # 👉️ 'hello' # 👇️ from index 6 (inclusive) to end print(my_str[6:]) # 👉️ 'world'

The first example shows how to get the first 5 characters from a string.

The second example starts at the character at index 6 and goes to the end of the string.

The syntax for string slicing is a_string[start:stop:step] .

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

If the start index is omitted, it is considered to be 0 , if the stop index is omitted, the slice goes to the end of the string.

# Working with nested dictionaries

Here is another example of how the error occurs.

Copied!
my_dict = 'a': 'name': 'Alice'>, 'b': 'Bobby' > # ⛔️ AttributeError: 'str' object has no attribute 'get' my_dict['b'].get()

The dictionary has some keys that point to a nested dictionary and some keys that point to a string.

Trying to call the dict.get() method on a string caused the error.

You can use a try/except statement to handle the error in the case the key points to a string and not a nested dictionary.

Copied!
my_dict = 'a': 'name': 'Alice'>, 'b': 'Bobby' > # ⛔️ AttributeError: 'str' object has no attribute 'get' try: print(my_dict['b'].get()) except AttributeError: pass

We try to call the get() method in the try statement and if an error is raised, the except block handles it.

# How to debug your code

A good way to start debugging is to print(dir(your_object)) and see what attributes a string has.

Here is an example of what printing the attributes of a string looks like.

Copied!
my_string = 'hello world' # [ '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))

If you pass a class to the dir() function, it returns a list of names of the class’s attributes, and recursively of the attributes of its bases.

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

Since get() is not a method implemented by strings, the error is caused.

If the error persists, follow the instructions in my AttributeError: ‘str’ object has no attribute ‘X in Python article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью