'Can I read dict using "user input"?

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"?

Thanks for your suggestions. I feel a bit enlightened! :) I also found a very good source:https://www.pythonpool.com/dictionary-to-list-python/ Peace to everyone!



Solution 1:[1]

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.

Solution 2:[2]

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.

Solution 3:[3]

Try this

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amirhossein Kiani
Solution 2
Solution 3