Home > Net >  Can I read dict using "user input"?
Can I read dict using "user input"?

Time:03-20

It works for my game:

import random

ships = {
    "transporter": {
        "type": "transporter", "price": 5000
    },
    "scout": {
        "type": "fighter", "price": 8000
    },
    "interceptor": {
        "type": "fighter", "price": 100003
    }
}

player_ship = random.choice(list(ships))
print(player_ship)

Is it possible to read key: value using input? E.g.

player_ship = input("Choose a ship:")

and when the user enters "1" he will choose "transporter"?

CodePudding user response:

Yes, it is possible:

userInput = int(input("Choose a ship: "))
print(ships[list(ships)[userInput-1]])

Example output #1

Choose a ship: 1
{'type': 'transporter', 'price': 5000}

Example output #2

Choose a ship: 2
{'type': 'fighter', 'price': 8000}

Note that, you have to define the ships beforehand.

CodePudding user response:

With current structure you have to do what @Amirhossein suggested. However, this entails to keep another list for keys.

If you're only going to use ships for this purpose, you could write ships this way:

ships = [{"name": "transporter", "type": "transporter", "price": 5000},
         {"name": "scout", "type": "fighter", "price": 8000},
         {"name": "interceptor", "type": "fighter", "price": 100003}]

then:

userInput = int(input("Choose a ship: "))
print(ships[userInput - 1]['name'])

Now you can access the list container easily by index.

CodePudding user response:

Try this

user_ship = int(input("Choose a ship:"))
list_of_ships = list(ships)
print(list_of_ships[user_ship - 1])
  • Related