+ 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!

5th Sep 2019, 5:12 AM
Jin
Jin - avatar
5 odpowiedzi
+ 1
Returns the last found element
6th Sep 2019, 12:45 AM
haydenki
haydenki - avatar
+ 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
5th Sep 2019, 5:27 AM
Trigger
Trigger - avatar
+ 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
6th Sep 2019, 9:26 AM
BlackRose Mike
BlackRose Mike - avatar
+ 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?
6th Sep 2019, 5:31 AM
Jin
Jin - avatar
+ 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!!
6th Sep 2019, 9:31 AM
Jin
Jin - avatar