What Does It Mean If a Python Object Is "Subscriptable" or Not

What does it mean if a Python object is subscriptable or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

Int object not subscriptable?

Subscriptable means that the object implements the __getitem__() method. In other words, it is for objects that are "containers" of other objects; such as strings, lists, tuples, or dictionaries.

A number cannot be accessed this way, you can try to convert it to a string, then access the first location and then convert it back to int for the sum operation, which is a little overcomplicated:

def get_funny_sum(num1, num2):
num1 = str(num1)
num2 = str(num2)
acc = int(num1[0]) + int(num2[0])
return acc

print(get_funny_sum(23, 45))

Or try to execute a division by powers of ten to get the proper digit that you want

Object is not subscriptable python error django

Keep in mind that in your for loop the variables d['start'] and d['end'] each contain an instance of the Start model. To manipulate the fields of an instance you should use the dot . (you should use subscript when dealing with subscriptable objects - see What does it mean if a Python object is "subscriptable" or not?):

data = {'[%s, %s] -> [%s, %s]' % (d['start'].latitude, 
d['start'].longitude, d['end'].latitude, d['end'].longitude)}

TypeError: 'type' object is not subscriptable during reading data

Looks like the problem is right in the type hint of one of your function parameters: dict[str, int]. As far as Python is concerned, [str, int] is a subscript of the type dict, but dict can't accept that subscript, hence your error message.

The fix is fairly simple. First, if you haven't done so already, add the following import statement above your function definition:

from typing import Dict

Then, change dict[str, int] to Dict[str, int].

Python - printing object error: object is not subscriptable

The problem is item[index].name - CartItem is not subscriptable as the error states. You don't need to use index, you iterate over list. Also you can simplify your __str__() method.

Note that using print() inside the __str__() method is bad. Better construct a string to describe the cart and return it. Also should have __repr__ instead of __str__() for CartItem. It will be used when you print items in container like list Cart.items. Also you can use the string representation of the Item when you construct the Cart.__str__()

class CartItem:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f'{self.name} --> {self.price}'


class Cart:
def __init__(self):
self.items = []

def __str__(self):
if self.items:
return '\n'.join(f'{idx}: {item}' for idx, item in enumerate(self.items))
return "Empty Cart"

def addItem(self, cartItem):
self.items.append(cartItem)
print(f'{cartItem.name}, costing ${cartItem.price}, has been added to cart')
print(self.items) # *should* print out the contents of the cart, but doesn't...


userCart = Cart()
print(userCart)
flarn = CartItem("flarn", "200.00")
print(flarn)
userCart.addItem(flarn)
flarn = CartItem("flarn", "100.00")
print(flarn)
userCart.addItem(flarn)
print(userCart)

output:

Empty Cart
flarn --> 200.00
flarn, costing $200.00, has been added to cart
[flarn --> 200.00]
flarn --> 100.00
flarn, costing $100.00, has been added to cart
[flarn --> 200.00, flarn --> 100.00]
0: flarn --> 200.00
1: flarn --> 100.00

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))


Related Topics



Leave a reply



Submit