+ 2
Python: have dictionary both upper and lower case?
Hi, I'm trying to build a dictionary, however, it seems to be cap specific. If entered "ICH" it will return a result, if entered "ich" then it shows an error. How can it be both "ICH" and "ich"? I've tried to add .lower in input, but it doesnt seem to work. ClinicalTerms={ "ICH" :"International Community of Harmonization", "AE":"Adverse Event", "SAE":"Severe Adverse Event", } print (ClinicalTerms.get(input("Enter your abbreviation: "), "Sorry, abbreviation not in dictionary"))
12 Réponses
+ 6
Here is what I would do (might be a bit over-complicated, but it works):
https://code.sololearn.com/cNbIkBsi39v9/?ref=app
+ 6
Anna Does this work the same way as your code?
for key, value in ClinicalTerms.items():
if key.lower() == user_input:
print(value)
break
else:
print("Sorry, abbreviation not in dictionary")
+ 6
I like the approach from a StackOverflow answer as implemented in this code:
https://code.sololearn.com/cz56k8XNmdU6/?ref=app
This approach extends the default Dictionary with a case insensitive version.
+ 6
Terry did you use = and not == in that line? Then that may be the reason.
+ 5
Diego Acero Yes, plus it's more compact and thumbs up-worthy 👌🤓 (I can't get used to the for... else syntax)
+ 4
Anna touché! Some abbreviations do use lowercase--should have thought of that.
+ 3
Also, isn't it better to turn user_input to upper once, than every key to lower?
+ 3
Kishalaya Saha I thought the dictionary might get extended and not every key has to be all uppercase 🤔
+ 3
@Kishalaya Saha
"Terry did you use = and not == in that line? Then that may be the reason."
arrrr ok thanks
+ 2
Thanks Anna, I see, very interesting
+ 2
Terry Did you try the solution I shared?
0
From Diego, is this what you had meant? Seems to receive error at if key.lower()=user_input:
ClinicalTerms={
"ICH" :"International Community of Harmonization",
"AE":"Adverse Event",
"SAE":"Severe Adverse Event",
}
user_input=input("Enter your abbreviation: ")
for key, value in ClinicalTerms.items():
if key.lower()=user_input:
print(value)
break
else:
("sorry")