Coder's Cat

Python: Dict setdefault and getdefault

2020-03-25

file:img/2020_03_25_python-set-default.org_20200326_000322.png

In this post, we will discuss dict’s setdefault and getdefault in Python.

These are two handy programming idioms in Python.

getdefault

When we get the value from a dict, if the key does not exist in dict, a None will be returned.

dict.get(key, default = None)

The second parameter for get is the default value. Here is an example:

dict = { 'Name': 'Nick', 'Age': 23 }
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Master")

# => Value : 23
# => Value : Master

setdefault

Suppose We have a dict which recording the result of a examination:

table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }

We want to convert it to a dict with grade -> list of names so that we can check how many students in each grade. The result will be:

{ "A" : ["Nick"], "B" : ["Ada", "Mike"], "C" : ["Leo"], "D" : ["Sandy"] }

A beginner maybe will write the code in this way:

table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
result = {}
for name, score in table.items():
if score not in result:
result[score] = [name]
else:
result[score].append(name)

print(result)

# => {'A': ['Nick'], 'C': ['Leo'], 'B': ['Mike', 'Ada'], 'D': ['Sandy']}

In each iteration, we need to check whether the new key exists in the result.

A more pythonic way is using setdefault :

table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
result = {}
for name, score in table.items():
g = result.setdefault(score, [])
g.append(name)

print(result)

# => {'A': ['Nick'], 'C': ['Leo'], 'B': ['Mike', 'Ada'], 'D': ['Sandy']}

The code can be more simpler if we use defaultdict, but the result is an object of defaultdict:

table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
from collections import defaultdict

result = defaultdict(list)
for name, score in table.items():
result[score].append(name) # all keys have a default already

print(type(result))
print(result)


# => <type 'collections.defaultdict'>
# => defaultdict(<type 'list'>, {'A': ['Nick'], 'C': ['Leo'], 'B': ['Mike', 'Ada'], 'D': ['Sandy']})

Join my Email List for more insights, It's Free!😋

Tags: Python