Dictionaries
In this lesson, you learned the pythonic way to retrieve data from dictionaries. Dictionary objects have a get()
method that allows you to retrieve data without raising errors when the requested data does not exist. get()
takes an optional default value as an argument.
The code sample below shows the correct way to retrieve data from a dictionary using get()
:
1dictionary = {'Mahdi': 5, 'Lizbon': 6}
2
3# dict.get() takes a second value as a default
4his_apples = dictionary.get('Mahdi', 0)
5her_apples = dictionary.get('Jennifer', 0)
Instead of raising a KeyError
, line 5 will simply return 0. This approach is much better than trying to access dictionary keys and then catching any errors that may arise.
00:00 Next thing we’re going to talk about is dictionary introspection.
00:05 Oftentimes when you’re dealing with dictionaries, you’re dealing with third-party tools which return all kinds of information from a particular endpoint.
00:15
The poor way of going about this is what you do is you look up the name of the key from the dictionary and assign it to his_apples
. And then we do something a little funky with 'Jennifer'
. Since she’s not in the initial dictionary, what we do is, to make sure that it actually returns a value, we put this in a try-catch block and we check to see if we’re able to access 'Jennifer'
. If we’re not, then we simply assign 0
to her_apples
and it ends up with something like this.
00:43
The better way of going about this is to use the .get()
that is provided in the dictionaries. And what the .get()
does, it simply provides a default value in case that the key ends up with a KeyError
.
00:58
So we have the dictionary, call .get()
, provide your key, and provide a value that it will return in case there’s a KeyError
.
01:10 And, as you can see, this is a much cleaner way of going about it and much more succinct as to what your default value would be.
Andras Novoszath on March 13, 2019
Maybe like this?
new_dict = {}
Learn2Improve on Feb. 4, 2020
Hey DanielHao5,
There are 2 ways to define empty dict:
# 1. option
new_dict = {}
# 2. option
new_dict = dict()
Hope it helps.
Become a Member to join the conversation.
DanielHao5 on March 13, 2019
Good Tips. Another question is - how to set the dictionary first? Meaning to initiaize the dictionary - more Pathonic way? Thanks.