DEV Community

Nic
Nic

Posted on • Originally published at coderscat.com on

Python: Dict setdefault and getdefault

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

setdefault

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

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

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"] }
Enter fullscreen mode Exit fullscreen mode

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']}

Enter fullscreen mode Exit fullscreen mode

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']}

Enter fullscreen mode Exit fullscreen mode

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']})

Enter fullscreen mode Exit fullscreen mode

The post Python: Dict setdefault and getdefault appeared first on Coder's Cat.

Top comments (0)