Reputation: 93
I'm reading a file and putting contents into dictionary. I'm writing a method where I search for key and return its value. How do I throw exception if my key is not present in dictionary. For example below is the code I'm testing but I get output of re.search as None for non-match items. Can I use has_key() method?
mylist = {'fruit':'apple','vegi':'carrot'}
for key,value in mylist.items():
found = re.search('vegi',key)
if found is None:
print("Not found")
else:
print("Found")
Found Not found
Upvotes: 1
Views: 1300
Reputation: 4010
@JRazor gave you several ways of using list comprehension, lambda and filter for doing what you call a "has_key() method" (I get SyntaxError
s when I copy/paste them to python 2.7 interpreter though?)
Here's the literal answer to your question: "How do I throw exception if my key is not present in dictionary?"
What many languages refer to as throw
(an exception), python calls raise
(an exception).
More info on that here.
In your case, you could add a custom exception like so:
mylist = {'fruit':'apple','vegi':'carrot'} # mylist is a dictionary. Just sayin'
if "key" not in mylist:
raise Exception("Key not found")
else:
print "Key found"
Upvotes: 0
Reputation: 1283
Python trends towards the "Easier to Ask Forgiveness than Permission" model versus "Look Before You Leap". So in your code, don't search for the key before trying to pull it's value, just pull for it's value and handle the fallout as needed (and where needed).
*Assuming you're asking how to find one key, and return it's value.
EAFP approach:
def some_func(key)
my_dict = {'fruit':'apple', 'vegi':'carrot'}
return my_dict[key] # Raises KeyError if key is not in my_dict
If a LBYP is what you have to do, try this:
def some_func(key):
my_dict = {'fruit':'apple', 'vegi':'carrot'}
if not key in my_dict:
raise SomeException('my useful exceptions message')
else:
return my_dict[key]
The biggest problem with the LBYP approach is that it introduces a race condition; the 'key' may or may not exist between checking for it, then returning it's value (which is only possible when doing current work).
Upvotes: 3
Reputation: 1854
You can simply use 'in'.
mylist = {'fruit':'apple','vegi':'carrot'}
test = ['fruit', 'vegi', 'veg']
for value in test:
if value in mylist:
print(value + ' is in the dict, its value : ' + mylist[value])
else:
raise Exception(value + ' not in dict.')
# Console
# fruit is in the dict, its value: apple
# vegi is in the dict, its value: carrot
# Exception: veg is not in dict
Upvotes: 1