+ 6
Python - What if a value to be looked up in the dictionary is not in the dictionary
Hi community I'm kind of a beginner of python programming and I wonder that: Say I have a dictionary which is Dictionary = {A:x, B:y}, what if I look up C in the dictionary? Does it return nothing or look up the value above (sort of like a VLOOKUP with a TRUE argument in Excel) Thanks for your help!
5 Answers
+ 1
Returns the last found element
+ 12
dictionary.get(value_you_want, value_if_not_found)
This is the method for getting a dictionary value. As you can see, the second parameter is to be returned if not found
+ 11
Jin if you use normal way of fetching a value i.e dict['c'] and the value not found it returns an error.
But if you use dict.get('c') and the second option not specified it returns None and the error is ignored.
you can as well fetch all keys and iterate through it.
keys = dict.keys()
or check if a key exist using
has_key('c') #returns True or False
or you can create a new key when a certain key dont exist
setdefault('c', 'as default')
PS: this are methods so you call i.e dict.has_key() etc
#HappyCoding
+ 1
Hi Haydenki
Can I please just check with you if my understanding is right:
If I don't specify a default value in the get method, it returns the last found value.
I think this is what I'm seeing in the outputs. However, how come an error of some sort wasn't raised?
I'm using the codes in the line of the following without a closing elseif or end:
if dictionary.get(type):
A = some calculation
Is it what's supposed to happen?
+ 1
Hey all
With the IF ststement per my reapose abvoe, it does NOT return none, it returns the last found value i.e. the value from the last look up for which a value can be found!!