spock
6/11/2017 - 11:25 AM

Dictionaries with default values.

Dictionaries with default values.

""" approaches 1 & 2 work on the standard dic"""
# approach 1: via dict.get()
dict default
dict.get('key', 'default')  # fallback insted of KeyError handling

# approach 2: via setdefault()
dict default
default.setdefault('my default value')

# approach 3: via defaultdic
from collections import defaultdict

ice_cream = defaultdict(lambda: 'default_value')