+ 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()))
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'))
+ 2
print(data.get(input()) or "Not found")
+ 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
+ 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
+ 1
None of these are working
+ 1
Bob_Li
I think it is for another post.
https://www.sololearn.com/Discuss/3252608/?ref=app
+ 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..
0
Oneshot
Does your code show any error message?
Please post your code so we can review it.
0
contacts = [
('James', 42),
('Amy', 24),
('John', 31),
('Amanda', 63),
('Bob', 18)
]
data=contacts
print(data.get(input())or "Not found")
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...