Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
dict with "missing" values
import collections
missing = object()
class MissingDict(dict):
"""Dictionary that supports a special 'missing' value.
Assigning a missing value to key will remove the key from dictionary.
Initializing a key with missing value will result in key not being
added to dictionary at all.
Rationale is to eliminate 'ifs' which are sometimes needed when creating
dictionaries e.g. when sometimes we want default value for keyword argument.
Example:
>>> MissingDict({
'zero': 0 or missing,
'one': 1,
})
{'one': 1}
"""
def __init__(self, arg=None, **kwargs):
if arg is None:
kwargs = dict((k, v) for k, v in kwargs.iteritems()
if v is not missing)
dict.__init__(self, **kwargs)
else:
items = (((k, arg[k]) for k in arg)
if isinstance(arg, collections.Mapping) else arg)
filtered_items = ((k, v) for k, v in items
if v is not missing)
dict.__init__(self, filtered_items)
def __setitem__(self, key, obj):
if obj is missing:
del self[key]
else:
dict.__setitem__(self, key, obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment