Daniel Ali
Daniel Ali

Reputation: 13

How do i call a dictionary value from user input

I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4. 

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2. how do I update the new value?

Upvotes: 1

Views: 4298

Answers (5)

Shaanbhaya
Shaanbhaya

Reputation: 21

I think what you are doing is printing the value of the input instead of value of the key in the dict. In dict there is a mapping between key and value. So if you want to print the value of the key 2 you need to ask the dict for the value of key 2.That is done by calling the dict with that particular key .So if we suppose you made a dict called weights like this `

weights ={1:0.5,2:1.2,3:1.7,4:2.4}

then to get the value for key 2, we need to call the weights with the following syntax.

value = weights[2]

Please check this code and run it to have a better understanding of the problem.

weights ={1:0.5,2:1.2,3:1.7,4:2.4}
user_input = 0 
while user_input not in (weights.keys()):
    user_input = input("Please input the value for weight between 1 to 4: ")
print("Value of weight = %s"%weights[user_input])

Upvotes: 0

abhiarora
abhiarora

Reputation: 10430

Here, you should do:

weight = int(input("Enter your Weight: "))

def getScale(weight):
    return {
        1 : 0.5,
        2 : 1.2,
        3 : 1.7,
        4 : 2.4
    }.get(weight, 0.5)


print(getScale(weight))

Using the second parameter of get(weight, 0.5), you can define what happens when value entered by user is not in the dict.

Upvotes: 1

oamandawi
oamandawi

Reputation: 369

Welcome to SO, Daniel!

If I understand correctly, you have 1, 2, 3, and 4 as keys corresponding to 0.5, 1.2, 1.7, and 2.4, respectively.

Since input is accepted as a string, we must convert it to integer, like so:

weights_dictionary = {1: 0.5, 2: 1.2, 3: 1.7, 4: 2.4}

user_weight = int(input("Enter weight from 1 to 4:"))

print(weights_dictionary[user_weight])

Upvotes: 1

Prashant Kumar
Prashant Kumar

Reputation: 2092

If you don't want to store the keys in your dictionary in string type, you will have to convert the user input (string) to integer.

Also, for printing the desired output you need to access the dictionary for value with a key. You can do that simply by : my_dict[key] . This will give you the value for key.

Try this :

weight_dict = {1 : 0.5, 2 : 1.2, 3 : 1.7, 4 : 2.4}

input = input("enter a weight: ")

input_weight = int(input.strip())

print("Weight on scale is : {0}".format(weight_dict[input_weight]))

Upvotes: 1

Sociopath
Sociopath

Reputation: 13401

IIUC you need

 scal3 = {"1":0.5, "2":1.2, "3":1.7, "4":2.4}

 n = input("enter a number: ")

 print(scal3[n])

or if you don't want it to throw error if user enters wrong key

print(scal3.get(n))

Upvotes: 2

Related Questions