inventory = {
'gold' : [500,50],
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'].sort(),'pocket': ['seashell','strange berry','lint']
}
del(inventory['backpack'][1])
inventory['backpack'].remove(1)
inventory['backpack'].remove(["backpack"][1])
Traceback (most recent call last):
File "python", line 6, in <module>
AttributeError: 'NoneType' object has no attribute 'remove'
['xylophone','dagger', 'bedroll','bread loaf'].sort()
returns None. Therefore 'NoneType' object has no attribute 'remove'
try
sorted(['xylophone','dagger', 'bedroll','bread loaf'])
instead.
Because you set 'backpack'
to this:
['xylophone','dagger', 'bedroll','bread loaf'].sort()
.sort()
sorts a list in-place and returns None
. So inventory['backpack']
is None
.
Either sort the list after you build the inventory:
inventory = ...
inventory['backpack'].sort()
Or use sorted
:
'backpack': list(sorted(['xylophone', 'dagger', 'bedroll', 'bread loaf'])),
.sort()
doesn't work this way, it changes the list but returns None
:
x = ['c', 'b', 'a']
x.sort()
print(x)
This code will output ['a', 'b', 'c']
, but this code will output None
:
x = ['c', 'b', 'a']
x = x.sort()
print(x)
To solve this problem, you have to change your code to:
backpack = ['xylophone','dagger', 'bedroll','bread loaf']
backpack.sort()
inventory = {
'gold' : [500,50],
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : backpack,'pocket': ['seashell','strange berry','lint']
}
Or:
inventory = {
'gold' : [500,50],
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : sorted(['xylophone','dagger', 'bedroll','bread loaf']),'pocket': ['seashell','strange berry','lint']
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.