Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary methods
#1
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.
Reply
#2
>>> 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.
...
>>>
Reply
#3
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:

val = d.get(key, 'default')
python documentation Wrote:dict.get = get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary Methods Wolfpack2605 2 2,293 Jan-28-2018, 12:51 AM
Last Post: league55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020