[Python] How can I get a value from a subdictionary from its key?

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a subdictionary for each item in my game and want to be able to get the name/description for whatever item in the inventory is selected by the player or output in the code (by output I mean for every item key in the inventory list, it prints the value I want).

    #Items dictionary
    items = {
    "spencer": {
    "name": "Spencer Repeating Rifle",
    "description": "The Spencer Repeating Rifle\nProduced by Burnside Rifle Co. in 1860",
    "cost": 10
    }
    }


    #Inventory
    inventory = ["walker", "spencer"]


    I want to be able to take the key for each item in the inventory list and output it's name from the subdictionary.

    This isn't the whole dictionary, just an example piece. Sorry if this is a really dumb question, I'm just starting on learning dictionaries.

    I tried:

    for item_key in inventory:
    print(f"{name}")


    This didn't work. The indent is probably wrong on that, it isn't letting me shift indent.

    Continue reading...

Compartilhe esta Página