Python nested dictionary error "string indices"

Question:

This code is intended to display the inventory when inventory_check is called, then enable the player to select any item from the list by using the item_mod variable to display the name, type, and examine dialogue from the corresponding dictionary item.

#  WEAPONS AND GEAR  #
dicts={"bronze sword": {
  "name": "Bronze Sword",
  "type": "weapon",
  "atk": "3",
  "examine": "A shiny bronze sword.",
},

"turian garb": {
  "name": "Turian Garb",
  "type": "Armour",
  "def": "1",
  "examine": "Your combat uniform.", 
},

"rusty buckler": {
  "name": "Rusty Buckler",
  "type": "Shield",
  "def": '1',
  "examine": "An old buckler, standard."
}, 
       
"test item": {
  "name": "test",
  "type": "weapon",
  "atk": '1',
  "examine": "Hope this works (:"
}        
}


######################
def inventory_check():
  os.system('clear')
  print(inventory)
  time.sleep(1)
  mid_print("How would you like to interact with the inventory? Type the item and then what to do with it. n")
  mid_print("You can also type exit to leave the inventory. n")
  print(inventory)
  item_mod = input(Green + "Which item to interact with? > n" + reset)
  if item_mod in inventory:
    print (item_mod["name"])
    print (item_mod["type"])
    print (item_mod["examine"])
  elif item_mod in ['leave', 'exit', 'e']:
    location_check()
  else:
    mid_print("That is not an item in your inventory. remember to punctuate correctly. n")
    inventory_check()

However, it refuses to run the code, claiming "string indices must be integers". I haven’t used integers, so am not sure where i have gone wrong. Thank you.

Asked By: Pr1sm

||

Answers:

I guess you want to do

if item_mod in inventory:
  print (inventory[item_mod]["name"])
  print (inventory[item_mod]["type"])
  print (inventory[item_mod]["examine"])

instead?

Answered By: C. Li
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.