[pythonvis] Re: Dictionary Question, Using the dictionary.get function or using if x in d

  • From: Dzhovani <dzhovani.chemishanov@xxxxxxxxx>
  • To: pythonvis@xxxxxxxxxxxxx
  • Date: Wed, 12 Oct 2016 23:53:22 +0300

If you use the "in" operator, under the hood the entire dictionary is
traversed to check for the value. If you use "get", there is only one
operation and you can always rely on working code.


On 12.10.2016 г. 21:37 ч., Jim wrote:

Hi,
I'm reading:
https://automatetheboringstuff.com/chapter5/

I'm not getting the point about the following piece of text.

Checking Whether a Key or Value Exists in a Dictionary
Recall from the previous chapter that the in and not in operators can
check whether a value exists in a list. You can also use these
operators to see whether a certain key or value exists in a
dictionary. Enter the following into the interactive shell:
spam = {'name': 'Zophie', 'age': 7}
'name' in spam.keys()
True
'Zophie' in spam.values()
True
'color' in spam.keys()
False
'color' not in spam.keys()
True
'color' in spam
False
In the previous example, notice that 'color' in spam is essentially a
shorter version of writing 'color' in spam.keys(). This is always the
case: If you ever want to check whether a value is (or isn’t) a key in
the dictionary, you can simply use the in (or not in) keyword with the
dictionary value itself.
The get() Method
It’s tedious to check whether a key exists in a dictionary before
accessing that key’s value. Fortunately, dictionaries have a get()
method that takes two arguments: the key of the value to retrieve and
a fallback value to return if that key does not exist.
Enter the following into the interactive shell:
picnicItems = {'apples': 5, 'cups': 2}
'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'
Because there is no 'eggs' key in the picnicItems dictionary, the
default value 0 is returned by the get() method. Without using get(),
the code would have caused an error message, such as in the following
example:
picnicItems = {'apples': 5, 'cups': 2}
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'

I'm not getting what makes using the get function, method, or whatever
the thing is called more efficient. The reason is that I'm still
saying to myself that I still have to see if get returned the thing I
put into the dictionary or the default value I supplied. What am I not
seeing here?

Thanks.

Jim



---
Този имейл е проверен за вируси от Avast.
https://www.avast.com/antivirus

List web page is 
//www.freelists.org/webpage/pythonvis

To unsubscribe, send email to 
pythonvis-request@xxxxxxxxxxxxx with "unsubscribe" in the Subject field.

Other related posts: