FlatDict¶
flatdict is a Python module for interacting with nested dicts as a single
level dict with delimited keys. flatdict supports Python 3.5+.
Jump to Installation, Example Use, or API Documentation.
For example:
value = flatdict.FlatDict({'foo': {'bar': 'baz', 'qux': 'corge'}})
can be accessed as:
value == {'foo:bar': 'baz', 'foo:qux': 'corge'}
values can be accessed as:
print(foo['foo:bar'])
# or
print(foo['foo']['bar'])
Additionally, lists and tuples are also converted into dicts using enumerate(),
using the FlatterDict class.
For example:
value = flatdict.FlatterDict({'list': ['a', 'b', 'c']})
will be flattened as follows:
value == {'list:0': 'a', 'list:1': 'b', 'list:2': 'c'}
Installation¶
$ pip install flatdict
Versioning¶
This package attempts to use semantic versioning. API changes are indicated by the major version, non-breaking improvements by the minor, and bug fixes in the revision.
It is recommended that you pin your targets to greater or equal to the current version and less than the next major version.
Example Use¶
import pprint
import flatdict
flat = flatdict.FlatDict(
{'foo': {'bar': {'baz': 0,
'qux': 1,
'corge': 2},
'grault': {'baz': 3,
'qux': 4,
'corge': 5}},
'garply': {'foo': 0, 'bar': 1, 'baz': 2, 'qux': {'corge': 3}}})
print(flat['foo:bar:baz'])
flat['test:value:key'] = 10
del flat['test']
for key in flat:
print(key)
for value in flat.itervalues():
print(value)
pprint.pprint(flat.as_dict())
pprint.pprint(dict(flat))
print(flat == flat.as_dict())
import flatdict
value = flatdict.FlatterDict({'list': ['a', 'b', 'c']})
for key, value in value.items():
print(key, value)
API Documentation¶
FlatDict is a dict object that allows for single level, delimited key/value pair mapping of nested dictionaries.
-
class
flatdict.FlatDict(value=None, delimiter=':', dict_class=<class 'dict'>)[source]¶ FlatDictis a dictionary object that allows for single level, delimited key/value pair mapping of nested dictionaries. The default delimiter value is:but can be changed in the constructor or by callingFlatDict.set_delimiter().-
copy()[source]¶ Return a shallow copy of the flat dictionary.
Return type: flatdict.FlatDict
-
get(key, d=None)[source]¶ Return the value for key if key is in the flat dictionary, else default. If default is not given, it defaults to
None, so that this method never raisesKeyError.Parameters: - key (mixed) – The key to get
- d (mixed) – The default value
Return type: mixed
-
items()[source]¶ Return a copy of the flat dictionary’s list of
(key, value)pairs.Note
CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary’s history of insertions and deletions.
Return type: list
-
iteritems()[source]¶ Return an iterator over the flat dictionary’s (key, value) pairs. See the note for
flatdict.FlatDict.items().Using
iteritems()while adding or deleting entries in the flat dictionary may raiseRuntimeErroror fail to iterate over all entries.Return type: Iterator Raises: RuntimeError
-
iterkeys()[source]¶ Iterate over the flat dictionary’s keys. See the note for
flatdict.FlatDict.items().Using
iterkeys()while adding or deleting entries in the flat dictionary may raiseRuntimeErroror fail to iterate over all entries.Return type: Iterator Raises: RuntimeError
-
itervalues()[source]¶ Return an iterator over the flat dictionary’s values. See the note
flatdict.FlatDict.items().Using
itervalues()while adding or deleting entries in the flat dictionary may raise aRuntimeErroror fail to iterate over all entries.Return type: Iterator Raises: RuntimeError
-
keys()[source]¶ Return a copy of the flat dictionary’s list of keys. See the note for
flatdict.FlatDict.items().Return type: list
-
pop(key, default=<object object>)[source]¶ If key is in the flat dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary,
KeyErroris raised.Parameters: - key (mixed) – The key name
- default (mixed) – The default value
Return type: mixed
-
popitem() → (k, v), remove and return some (key, value) pair¶ as a 2-tuple; but raise KeyError if D is empty.
-
set_delimiter(delimiter)[source]¶ Override the default or passed in delimiter with a new value. If the requested delimiter already exists in a key, a
ValueErrorwill be raised.Parameters: delimiter (str) – The delimiter to use Raises: ValueError
-
setdefault(key, default)[source]¶ If key is in the flat dictionary, return its value. If not, insert key with a value of default and return default. default defaults to
None.Parameters: - key (mixed) – The key name
- default (mixed) – The default value
Return type: mixed
-
update(other=None, **kwargs)[source]¶ Update the flat dictionary with the key/value pairs from other, overwriting existing keys.
update()accepts either another flat dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the flat dictionary is then updated with those key/value pairs:d.update(red=1, blue=2).Parameters: other (iterable) – Iterable of key, value pairs Return type: None
-
values()[source]¶ Return a copy of the flat dictionary’s list of values. See the note for
flatdict.FlatDict.items().Return type: list
-
-
class
flatdict.FlatterDict(value=None, delimiter=':', dict_class=<class 'dict'>)[source]¶ Like
FlatDictbut also coerces lists and sets to child-dict instances with the offset as the key. Alternative to the implementation added in v1.2 of FlatDict.-
as_dict()[source]¶ Return the
FlatterDictas a nesteddict.Return type: dict
-
clear()¶ Remove all items from the flat dictionary.
-
copy()¶ Return a shallow copy of the flat dictionary.
Return type: flatdict.FlatDict
-
get(key, d=None)¶ Return the value for key if key is in the flat dictionary, else default. If default is not given, it defaults to
None, so that this method never raisesKeyError.Parameters: - key (mixed) – The key to get
- d (mixed) – The default value
Return type: mixed
-
items()¶ Return a copy of the flat dictionary’s list of
(key, value)pairs.Note
CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the flat dictionary’s history of insertions and deletions.
Return type: list
-
iteritems()¶ Return an iterator over the flat dictionary’s (key, value) pairs. See the note for
flatdict.FlatDict.items().Using
iteritems()while adding or deleting entries in the flat dictionary may raiseRuntimeErroror fail to iterate over all entries.Return type: Iterator Raises: RuntimeError
-
iterkeys()¶ Iterate over the flat dictionary’s keys. See the note for
flatdict.FlatDict.items().Using
iterkeys()while adding or deleting entries in the flat dictionary may raiseRuntimeErroror fail to iterate over all entries.Return type: Iterator Raises: RuntimeError
-
itervalues()¶ Return an iterator over the flat dictionary’s values. See the note
flatdict.FlatDict.items().Using
itervalues()while adding or deleting entries in the flat dictionary may raise aRuntimeErroror fail to iterate over all entries.Return type: Iterator Raises: RuntimeError
-
keys()¶ Return a copy of the flat dictionary’s list of keys. See the note for
flatdict.FlatDict.items().Return type: list
-
pop(key, default=<object object>)¶ If key is in the flat dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary,
KeyErroris raised.Parameters: - key (mixed) – The key name
- default (mixed) – The default value
Return type: mixed
-
popitem() → (k, v), remove and return some (key, value) pair¶ as a 2-tuple; but raise KeyError if D is empty.
-
set_delimiter(delimiter)¶ Override the default or passed in delimiter with a new value. If the requested delimiter already exists in a key, a
ValueErrorwill be raised.Parameters: delimiter (str) – The delimiter to use Raises: ValueError
-
setdefault(key, default)¶ If key is in the flat dictionary, return its value. If not, insert key with a value of default and return default. default defaults to
None.Parameters: - key (mixed) – The key name
- default (mixed) – The default value
Return type: mixed
-
update(other=None, **kwargs)¶ Update the flat dictionary with the key/value pairs from other, overwriting existing keys.
update()accepts either another flat dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the flat dictionary is then updated with those key/value pairs:d.update(red=1, blue=2).Parameters: other (iterable) – Iterable of key, value pairs Return type: None
-
values()¶ Return a copy of the flat dictionary’s list of values. See the note for
flatdict.FlatDict.items().Return type: list
-