kirsty hattersley
kirsty hattersley

Reputation: 45

Formatting Dictionaries

In the following example program, I'd like to have user input as a single character mapped to the full word: e.g. 's': 'small'. I'm not sure where to put it though. What I'm trying to get is:

~/Desktop$ python3 test.py 
Do you want to hire a bike or a car (b, c): b
Small, medium or large (s, m, l): s
Which colour? Red or yellow (r, y): r
Do you want normal or turbo speed (n, t): t
You chose: bike
You chose: colour: red
You chose: speed: normal
You chose: size: small

Here is the code:

def hire_bike():
    choices = {}
    choices['type'] = 'bike'
    choices['size'] = input('Small, medium or large (s, m, l): ')
    choices['colour'] = input('Which colour? Red or yellow (r, y): ')
    choices['speed'] = input('Do you want normal or turbo speed (n, t): ')
    return choices

def hire_car():
    choices = {}
    choices['type'] = 'car'
    choices['colour'] = input('Which colour? Black or white (b, w): ')
    choices['speed'] = input('Do you want normal or turbo speed (n, t): ')
    return choices

def menu():
    hire = input('Do you want to hire a bike or a car (b, c): ')
    if 'b' in hire:
        return hire_bike()
    elif 'c' in hire:
        return hire_car()

x = menu()

for k, v in x.items():
    print('You chose: {}'.format(v))

The output is:

~/Desktop$ python3 test.py 
Do you want to hire a bike or a car (b, c): b
Small, medium or large (s, m, l): s
Which colour? Red or yellow (r, y): r
Do you want normal or turbo speed (n, t): t
You chose: s
You chose: r
You chose: bike
You chose: t

Is there is a standard way of doing this sort of thing?

Upvotes: 0

Views: 52

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

choices['colour'] = input('Which colour? Black or white (b, w): ')

You are just storing the single character inputted by the user, instead of its corresponding "full" value. ('l' --> 'large')

# Mappings of user input to its corresponding values
sizes = {
    's': 'small',
    'm': 'medium',
    'l': 'large',
}

colours = {
    'r': 'red',
    'y': 'yellow'
}

speeds = {
    'n': 'normal',
    't': 'turbo'
}


def hire_bike():
    size = input('Small, medium or large (s, m, l): ').lower()
    colour = input('Which colour? Red or yellow (r, y): ').lower()
    speed = input('Do you want normal or turbo speed (n, t): ').lower()
    return {
        'type': 'bike',
        'size': sizes.get(size), # or sizes.get(size, 'default size') 
        'colour': colours.get(colour), # or colours.get(colour, 'default colour') 
        'speed': speeds.get(speed) # or speeds.get(speed, 'default speed') 
    }

this shall set the corresponding values to choices['size'], choices['colour'], choices['speed'] according to the user's input.

(Do the same for the hire_car() function)

Upvotes: 2

Related Questions