简体   繁体   中英

Remove item from list that present in dictionary

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']
}

for removing 'dagger' in the list stored in the 'backpack' key, i tried:

del(inventory['backpack'][1])

and

inventory['backpack'].remove(1)

and

inventory['backpack'].remove(["backpack"][1])

But stil the error

Traceback (most recent call last):
  File "python", line 6, in <module>
AttributeError: 'NoneType' object has no attribute 'remove'

What should I do ?

['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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM