Get the value while specifying the default value from dict in Python

I'll forget it soon, so make a note.

When retrieving a value from a dict instance with a key

If you think about it, it is good to use the get method.

>>> d = {"a": 1, "b": 2} 

>>> d["c"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'

>>> d.get("c") #Returns None if default is not specified

>>> d.get("c", 3) #If default is specified, that value will be returned.
3

>>> 

The nice thing is that you can specify get (key [, default]) and the default value. So you can easily write anything like the following with get.

>>> c = d["c"] if "c" in d else 3
>>> c
3

>>> c = d["c"] if d.has_key("c") else 3
>>> c
3

#The above guys can write neatly with the default specification of get
>>> c = d.get("c", 3)
>>> c
3

In addition, the following processing, which was imported defaultdict in order to write neatly, can also be written with get. However, it is better to use defaultdict, so if you want to improve readability, you should use defaultdict.

>>> from collections import defaultdict
>>> dd = defaultdict(int, d)
>>> dd
defaultdict(<type 'int'>, {'a': 1, 'b': 2})

>>> dd["c"] += 1  #To a key that does not exist+=No error occurs even if 1 is set, and the default value 0 of int is implicitly set.
>>> dd["c"]
1

#You can write without using defaultdict by using get
>>> d  
{'a': 1, 'b': 2}

>>> d["c"] = d.get("c", 0) + 1 #Get the default value 0 from a non-existent key+1 do
>>> d["c"]
1

Recommended Posts

Get the value while specifying the default value from dict in Python
Get the result in dict format with Python psycopg2
Get the value selected in Selenium Python VBA pull-down
Get your heart rate from the fitbit API in Python!
Get the value of a specific key in a list from the dictionary type in the list with Python
Get data from Quandl in Python
Get the desktop path in Python
Get the script path in Python
How to get the last (last) value in a list in Python
Get the value from the [Django] Form
Get the desktop path in Python
Get the host name in Python
Get exchange rates from open exchange rates in Python
Get battery level from SwitchBot in Python
Get the EDINET code list in Python
Get Precipitation Probability from XML in Python
[Python] Get the main color from the screenshot
Get metric history from MLflow in Python
Get time series data from k-db.com in Python
[Python] Get the files in a folder with Python
Get the caller of a function in Python
Get the X Window System window title in Python
How to get the files in the [Python] folder
Get only articles from web pages in Python
Isn't there a default value in the dictionary?
Get date in Python
Download the file while viewing the progress in Python 3.x
How to retrieve the nth largest value in Python
How to get the variable name itself in python
[Python] Get the text of the law from the e-GOV Law API
[Python] Get the numbers in the graph image with OCR
Output the time from the time the program was started in python
[python] Get the list of classes defined in the module
Get environment variables in Python, otherwise set default values
Get data from GPS module at 10Hz in Python
Get the return code of the Python script from bat
Find the part that is 575 from Wikipedia in Python
Get the size (number of elements) of UnionFind in Python
[Python] Get element by specifying name attribute in BeautifulSoup
Get the URL of the HTTP redirect destination in Python
Code that sets the default value in case of AttributeError
Get last month in python
Download the file in Python
Find the difference in Python
Shapley value calculation in Python
OCR from PDF in Python
Get the value of a specific key up to the specified index in the dictionary list in Python
Get the MIME type in Python and determine the file format
Get the number of specific elements in a python list
Use list-keyed dict in Python
The story that `while queue` did not work in python
Get Terminal size in Python
[Python] Get the previous month
Explicitly get EOF in python
Get index of nth largest / smallest value in list in Python
Automatically get the port where Arduino is stuck in Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
Get the current date and time in Python, considering the time difference
Hit REST in Python to get data from New Relic
Get macro constants from C (++) header file (.h) in Python
Get Evernote notes in Python