Jan-04-2018, 01:12 AM
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:
sounds = {'dog': 'a barker', 'cat': 'a meower', 'bird': 'a tweeter'}
print('cat' in sounds)
print('mouse' in sounds)
True
False
Sometimes you will need to either retrieve the value for a particular key from the dictionary or use a default value if the key doesn't exist. This typically takes 3 lines of Python:
val = 'default'
if key in d:
val = d[key]
However, this "use a default value if the key is not in the dictionary" pattern is so common, dictionaries provide the get method to do this:
val = d.get(key, 'default')
The first argument to get is the key. If the key is in the dictionary then the corresponding value is returned, otherwise, the second argument to get (here 'default') is returned.