Home > Software design >  Pulling items from dictionary and adding to a new list. (Python)
Pulling items from dictionary and adding to a new list. (Python)

Time:10-18

I am hoping that someone can help me to figure out why this code to add an item from the dictionary to a new list called 'inventory' will not work. This is the error message that I receive: Traceback (most recent call last): File "C:/filenameblahblahblah", line 71, in inventory.append(rooms(current_room['item'])) TypeError: 'dict' object is not callable. This is for a game that I have to create for class, and this is the only part of the game that isn't working for me. I need to add the 'item' to the list 'inventory' and then remove the 'item' from the dictionary 'rooms'. I apologize in advance if I do not have the sample of the code formatted properly, as I am still learning. Thanks in advance.

sample of my dictionary

rooms = {
'Cabin A': {'name': 'Cabin A', 'go starboard': 'Stern', 'item': 'Spearhead', 'item name': 'a 
    Spearhead'}, 
'Cabin B': {'name': 'Cabin B', 'go port': 'Hull', 'item': 'Spear Gun', 'item name': 'a Spear 
    Gun'}
        }

sample of what I have so far to try to pull from dictionary to add to list:

current_room = ['Cabin A']
inventory = []
if command in get_items:
    if 'item' in current_room:
        inventory.append(rooms(current_room['item']))
        del rooms[current_room['item']]
        rooms[current_room].update
        print(inventory)
    else:
        print('Nothing here.')

CodePudding user response:

This part of the code:

if 'item' in current_room:

is actually:

if 'item' in ['Cabin A']:

In other words, you are checking if the string 'item' is part of the list ['Cabin A'], which is not.

Secondly, the part:

rooms(current_room['item'])

will not work. rooms is a dictionary. You cannot call a dictionary rooms(), instead you need to do rooms['Cabin A']. Therefore, you could instead try:

rooms[current_room]['item']

where current_room='Cabin A'

The following should work:

inventory = []
for room in rooms:
    if "item" in rooms[room]:
       inventory.append(rooms[room]["item"])
       rooms[room].pop("item")
       print(inventory)
    else:
       print('Nothing here')

CodePudding user response:

Dictionaries are supposed to be accessed like dict[key] to get a value. Lists are supposed to be accessed like list[index] where index is an integer representing the index of the list value you're trying to access.

Notice:

inventory.append(rooms(current_room['item']))

You're using parentheses to access a rooms value. You're also trying to access the list current_room as if it's a dictionary.

  • Related