Looking for python Answers? Try Ask4KnowledgeBase
Looking for python Keywords? Try Ask4Keywords

Python Language Dictionary with default values


Example

Available in the standard library as defaultdict

from collections import defaultdict

d = defaultdict(int)
d['key']                         # 0
d['key'] = 5
d['key']                         # 5

d = defaultdict(lambda: 'empty')
d['key']                         # 'empty'
d['key'] = 'full'
d['key']                         # 'full'

[*] Alternatively, if you must use the built-in dict class, using dict.setdefault() will allow you to create a default whenever you access a key that did not exist before:

>>> d = {}
{}
>>> d.setdefault('Another_key', []).append("This worked!")
>>> d
{'Another_key': ['This worked!']}

Keep in mind that if you have many values to add, dict.setdefault() will create a new instance of the initial value (in this example a []) every time it's called - which may create unnecessary workloads.

[*] Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly). Copyright 2013 David Beazley and Brian Jones, 978-1-449-34037-7.