-3
monthConversions={
    "Jan":"January", #key:value
    "Feb":'February', #make sure keys are unique
    'Mar':'March', #can also use integers
    'Apr':"April",
    'May':'May',
    'Jun':'June',

}
print(monthConversions['Jan']) #gives value associated with the key
print(monthConversions.get('Luv','not a valid key'))

Hi, I am currently learning python through freebootcamp on youtube, and the person mentioned we can use the get function to pass in a value for a key that is not in the dictionary. I kind of understand that, but I fail to see what the use of this would be. I thought it would add Luv in when I put in

print(monthConversions['Luv'])

but it instead gives a error. What would be the purpose of the get function in this situation anyway? It feels like extra work and I don't get how it would be useful. Any explanations would be greatly appreciated, thank you.

Rachel Kim
  • 85
  • 5
  • 3
    Haven't you answered your own question? *"but it instead gives a error"* — If you don't want an error, you use `.get()`. – deceze Jan 09 '20 at 08:28
  • 1
    You've misunderstood what `get()` does, It doesn't insert a missing key, just ensures that *something* is returned, rather than raise an exception. The default is to return `None`, which you can check for. See the [documentation](https://docs.python.org/3/library/stdtypes.html#dict.get) – SiHa Jan 09 '20 at 08:31
  • In general terms, error, unless caught separately, will break the process. In order to always make sure the `dict[key]` works, you need to do a membership test (i.e. `if key in dict; dict[key]`. It will be the _extra work_ to either catch `KeyError` or do membership test all the time. Instead, you can use `dict.get`. – Chris Jan 09 '20 at 08:31

1 Answers1

0

It does not change the dict. The second argument is simply what get() returns when key is not found. If you don't specify it, it will simply return None.

bipll
  • 11,747
  • 1
  • 18
  • 32