+ 2

How do I get it to print "Not found" if the input isn't there?

data = { 'Singapore': 1, 'Ireland': 6, 'United Kingdom': 7, 'Germany': 27, 'Armenia': 34, 'United States': 17, 'Canada': 9, 'Italy': 74 } print(data.get(input()))

19th Nov 2023, 10:33 PM
Oneshot
Oneshot - avatar
10 Answers
+ 5
dictionary.get() accepts a second argument that is returned if the item is not found. So you can alternatively skip the or and write: print(data.get(input(), 'Not found'))
19th Nov 2023, 11:39 PM
Bob_Li
Bob_Li - avatar
+ 2
print(data.get(input()) or "Not found")
19th Nov 2023, 11:16 PM
Jan
Jan - avatar
+ 2
Although not related to your question, besides the "get" method, there are others handy dict methods you may want to know. https://code.sololearn.com/ci0n35S5m15K/?ref=app
20th Nov 2023, 1:32 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
Wong Hei Ming yes, with dictionary and get, it's almost like a mini OOP without creating classes... objects are basically dictionaries. setdefault is a nice nondestructive way to set values. One problem I feel is that it fails quietly. You don't know whether the new value is set or not unless you check. Since we are in the topic of dictionary, here is a way of creating immutable dictionary in Python I just learned https://code.sololearn.com/cUwHqFw32nhi/?ref=app
20th Nov 2023, 1:38 AM
Bob_Li
Bob_Li - avatar
+ 1
None of these are working
7th Dec 2023, 4:44 AM
Oneshot
Oneshot - avatar
7th Dec 2023, 9:34 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
Wong Hei Ming your link is for this post... 😅. But yes, I found the post you were referring to. https://www.sololearn.com/Discuss/3255314/?ref=app OP must really be confused..
7th Dec 2023, 11:08 AM
Bob_Li
Bob_Li - avatar
0
Oneshot Does your code show any error message? Please post your code so we can review it.
7th Dec 2023, 4:50 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] data=contacts print(data.get(input())or "Not found")
7th Dec 2023, 9:20 AM
Oneshot
Oneshot - avatar
0
Oneshot you now have a list of tuples. But you're still using a dict method. modify your code to this: data=dict(contacts) Then you have a proper dict...
7th Dec 2023, 9:31 AM
Bob_Li
Bob_Li - avatar