Sunday 11 October 2015

Python Data Structure -- defaultdict()

When using the original Python data structure -- dict(), there will be exception for KeyError if the key doesn't exist when accessing by d[key]. But with difaultdict(), only with a default factory function, it will be used as the default value of the key if the key does not exist. 
# -*- coding: utf-8 -*-
from collections import defaultdict

members = [
    # Age, name
    ['male', 'John'],
    ['male', 'Jack'],
    ['female', 'Lily'],
    ['male', 'Pony'],
    ['female', 'Lucy'],
]

result = defaultdict(list)
for sex, name in members:
    result[sex].append(name)

print result

# Result:
defaultdict(<type 'list'>, {'male': ['John', 'Jack', 'Pony'], 'female': ['Lily', 'Lucy']})

No comments:

Post a Comment