Dictionary methods - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Dictionary methods (/thread-7321.html) |
Dictionary methods - Wolfpack2605 - Jan-04-2018 Can someone please explain what is happening here. I have no clue what val is or what .get is. Please explain. Quote:Earlier in this module we looked at how to check if an element is in a dictionary, to protect against KeyErrors: RE: Dictionary methods - Mekire - Jan-04-2018 >>> d = {"a" : 1, "b" : 2, "c" : 3} >>> >>> d["b"] 2 >>> # But if we try an item not in d we get an exception ... >>> d["e"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'e' >>> # If we know this will happen and want a default vaule we can use get instead ... >>> d.get("a", "not found") 1 >>> # a is in the dict so we find it as expected ... >>> d.get("e", "not found") 'not found' >>> # e isn't in the dict so we get the default value instead. ... >>> RE: Dictionary methods - jajjaja - Jan-05-2018 Wolfpack2605 Wrote:I have no clue what val is or what .get is. Please explain.val is merely the variable name the example chose to use here. .get is a method provided by dictionaries your example Wrote:dictionaries provide the get method to do this: python documentation Wrote:dict.get = get(...)So calling d.get(key, 'default') returns the value of the key (if the key exists in the dictionary), or 'default' (if the key does not exist). After running your example which I quoted, val will contain what is returned. |