So I have a code for my dictionary:
def get_rooms_for(dict1, num):
try:
for x in dict1:
if x == num:
print(dict1[x])
except KeyError:
print (num,"is not available.")
And my test is
get_rooms_for({'CS101':3004, 'CS102':4501, 'CS103':6755,'NT110':1244, 'CM241':1411}, 'CS999')
And I expect my result is to print out 'num' parameter with string saying
CS999 is not available.
But when I put it this it returns empty What should i have to do if I want to pick an KeyError in dictionary, using exception code??
When you enter the try
loop you're then looping over all the keys in the dictionary. CS999
isn't a key in the dictionary, so you never try to access it. Thus you never hit a KeyError
, and the except
clause is never reached.
What you want to do is more like this:
def get_rooms_for(dict1, num):
if num in dict1:
print(dict1[num])
else:
print("{} is not available".format(num))
But Python already has a method for that: get
dict1.get(num, "{} is not available".format(num))
Which will return the value mapped to num
if it's in the dictionary, and "{} is not available".format(num)
if it's not.
Try this :
def get_rooms_for(dict1, num):
try:
for x in dict1:
if dict1[num] == x:
print "It will print particular key's {0} value if its exists or It will generate keyerror".format(dict1[num])
print(dict1[x])
except KeyError:
print (num,"is not available.")
Output :
('CS999', 'is not available.')
try this one :
def get_rooms_for(dict1, num):
try:
print(dict1[num])
except KeyError:
print (num,"is not available.")
You also can try without try
and exception
:
def get_rooms_for(dict1, num):
if dict1.has_key(str(num)): # or str(num) in dict1
print "Key available"
else:
print num,"is not available."
get_rooms_for({'CS101':3004, 'CS102':4501, 'CS103':6755,'NT110':1244, 'CM241':1411}, 'CS999')
output:
CS999 is not available.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.