Home > OS >  How to output one value from a dictionary whose key has two values
How to output one value from a dictionary whose key has two values

Time:04-14

I'm working on a text-based game project for school and I'm trying to pull one value from my dictionary. The value I'm trying to pull is "gun" and not both "Lobby" and "gun". The output is: "You see: Lobby Gun". The output I want is: "You see: Gun". Is that possible? Thank you.

rooms = {
        'Lobby': {'North': 'Teller Room', 'South': 'Vestibule', 'East': 'Office 1', 'West': 'Office 2'},
         'Vestibule': {'North': 'Lobby'},
        'Office 2': {'East': 'Lobby', 'Item': 'Gun'},
         'Office 1': {'North': 'Bathroom', 'Item': 'Gloves'},
         'Bathroom': {'West': 'Lobby', 'Item': 'Keys'},
         'Teller Room': {'South': 'Lobby', 'East': 'Utility Room', 'West': 'Vault', 'Item': 'Bags'},
        'Utility Room': {'West': 'Teller Room', 'Item': 'Knife'},
         'Vault': {'East': 'Teller Room', 'Item': 'Money'}

}


   collection = rooms['Office 2'].values()
   print('You see: ', *collection)

CodePudding user response:

If all you want to print is the item, then you should just print the item:

collection = rooms['Office 2']['Item']

Since not all rooms have an item, you'll need to check that.

CodePudding user response:

How to output one value from a dictionary whose key has two values

This appears to be a misunderstanding. All dictionary keys always have one value. In other words, when you do rooms['Office 2'], you only get one value. In this case, that value is another dictionary with its own keys an values. So when you do rooms['Office 2'].values(), you will get all of the values from the dictionary referred by rooms['Office 2'].

If that's not what you want, you should do something different with that dictionary such as only print out the item with print(rooms['Office 2']['Item']). You might want to update your inner dictionaries so that they all have an 'Item' key. If there is no item in the room, you can add 'Item': None to indicate this.

Side note, now that you are getting the hang of dictionaries, you should learn about classes. They provide a mechanism to represent objects in your game directly in code. For example, you could make class Room to represent a room in the game. This is often preferred over dictionaries because you can encapsulate data and behavior in a class.

  • Related