0

How can multiple keys have a value?

Example : # Just a small example don't try to debug this, I want to not use "if" Inp = int(input()) dic = { '''Inp between 1 and 9''' : "One digit", '''Inp between 10 and 99''' : "Two digit" } Print (dic[Inp])

25th Feb 2021, 6:48 PM
Sadra Shakouri
Sadra Shakouri - avatar
10 odpowiedzi
+ 4
https://code.sololearn.com/cBUny24kf4c7/?ref=app Swift edit: update to onelined print (initial code commented)
25th Feb 2021, 8:09 PM
visph
visph - avatar
+ 3
your question is unclear... try to be more descriptive, and/or provide real code ^^
25th Feb 2021, 7:03 PM
visph
visph - avatar
+ 2
no, range objects are not valid keys, and even if it was, bmi is not a range but a number ^^ I undestand that you try to emulate a 'switch' statement (not available in python): there could be possible to do such things, but I think you have to deal with 'if' as alternative solutions must be a little bit more tricky ;)
25th Feb 2021, 7:19 PM
visph
visph - avatar
+ 2
even with a switch statement, you couldn't use range ^^ for a bunch of ranges to be tested, you should use a structure combining a range and a function at each item, iterate over it and testing value against range... if test return true you can use the return value of the associated function ;) Swift edit: you could associate just a value instead of a function, obviously...
25th Feb 2021, 7:33 PM
visph
visph - avatar
+ 1
madeline the code is just an example, i could make it WAAAY easier : https://code.sololearn.com/c38g46aS5n3u/?ref=app
25th Feb 2021, 7:45 PM
Sadra Shakouri
Sadra Shakouri - avatar
+ 1
Swift so did you figure it out?
25th Feb 2021, 7:49 PM
madeline
madeline - avatar
0
madeline I wanted to know if i can replace "if" with dictionaries in all cases. Sadly there is no way in Python
25th Feb 2021, 7:52 PM
Sadra Shakouri
Sadra Shakouri - avatar
0
in fact, python3 accept range as keys (in python2 you should use xrange to get immutable)... anyway: 1) you cannot define range with float, only integer boundaries 2) you should iterate over dict keys and check if value is in range, as accessing a dict with ranges as keys would not have values for numerical keys (unless you define some): key error will be raised...
26th Feb 2021, 6:25 PM
visph
visph - avatar
- 1
visph one of the practice codes by sololearn which is a bmi calculator : w = int(input()) h = float(input()) bmi = w/(h**2) dic = { range(18.5) : "Underweight", range(18.5,25) : "Normal", range(25,30) : "Overweight", range(30,100) : "Obesity" } print(dic[bmi])
25th Feb 2021, 7:14 PM
Sadra Shakouri
Sadra Shakouri - avatar
- 1
visph thanks, if is hard in more situations (over 10 possibilities) but there is nothing that i can do
25th Feb 2021, 7:28 PM
Sadra Shakouri
Sadra Shakouri - avatar