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

  • From: Jim <jhomme1028@xxxxxxxxx>
  • To: pythonvis@xxxxxxxxxxxxx
  • Date: Thu, 13 Oct 2016 19:00:50 -0400

Hi Jeff,
I'm just trying to learn how this works. I went back through the
example again today and I understand it now.

Thanks.

Jim

On 10/13/16, Jeffrey Thompson <jthomp@xxxxxxxxxxx> wrote:

Jim,

"Get()" is useful when the programmer doesn't care if "eggs" is a key in the
dictionary, but a default value will  act as a substitute for key:value
pair.
In the "eggs" example this works because if there is no egg key then there
are 0 eggs.Should the programmer want to do something different, e.g.
add an "eggs" key if there isn't one, then the "get" method will not meet
the need.
The programmer would have to write something like:
# begin code
if 'X' not in dict:
      dict.update({'X':0})
              continue
      # end if
# end code

So "get()' may not meet the programmer's need in all situations;
If such is the case, then
the programmer can use "if "X" in dict: ...

If the programmer can use it, "get()"
is one line instead of two, less typing,
and probably noticeably faster if the programmer has a large
dictionary.Should the programmerhave several of these to write out, the
"get()" will be less tedious to type out than the "if 'X' in dict".

If the programmer is having a few or more such code snippets to type out,
the programmer might want to consider writing a function to handle the
problem.
# code begin
def Dict_update(theKey, theDict, aValue = 0):
    If theKey not in theDict.keys():
        theDict.update({theKey:aValue})
    return
# end function Dict_update()
# end code

This saves programmer time makes it easier to change when required to do
so.
(i.e. the programmer changes the interior of the function rather than going
through severalplaces in her/his code that will have to separately change.
The one disadvantage to such a solution (i.e. using a function) is that
function calls can slow down the process considerably.
If the programmer is working with relatively small data sets then the extra
drag will probably not be noticeable.Either way one does it, the process
should complete within a small fraction of a second.

Jim, I am curious. What are you trying to do that "get" will not satisfy?

      Hope that helps,

      Jet (Jeffrey Thompson)
      jthomp@xxxxxxxxxxx

-----Original Message-----
From: pythonvis-bounce@xxxxxxxxxxxxx [mailto:pythonvis-bounce@xxxxxxxxxxxxx]
On Behalf Of Jim
Sent: Wednesday, October 12, 2016 2:37 PM
To: pythonvis
Subject: [pythonvis] Dictionary Question, Using the dictionary.get function
or using if x in d

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

--
==========

Jim Homme
http://www.jimhommewebdev.com
Twitter: @jimhomme
Facebook: http://www.facebook.com/jimhomme
LinkedIn: https://www.linkedin.com/in/jimhomme
List web page is
//www.freelists.org/webpage/pythonvis

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

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

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



-- 
==========

Jim Homme
http://www.jimhommewebdev.com
Twitter: @jimhomme
Facebook: http://www.facebook.com/jimhomme
LinkedIn: https://www.linkedin.com/in/jimhomme
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: