1 """FlatDict is a dict object that allows for single level, delimited 2 key/value pair mapping of nested dictionaries. 19 """:class:`~flatdict.FlatDict` is a dictionary object that allows for 20 single level, delimited key/value pair mapping of nested dictionaries. 21 The default delimiter value is ``:`` but can be changed in the constructor 22 or by calling :meth:`FlatDict.set_delimiter`. 34 """Check to see if the key exists, checking for both delimited and 35 not delimited key values. 37 :param mixed key: The key to check for 46 """Delete the item for the specified key, automatically dealing with 49 :param mixed key: The key to use 64 """Check for equality against the other value 66 :param other: The value to compare 72 if isinstance(other, dict):
73 return sorted(self.
as_dict()) == sorted(other)
74 elif not isinstance(other, self.__class__):
76 return sorted(self.
as_dict()) == sorted(other.as_dict())
79 """Check for inequality against the other value 81 :param other: The value to compare 82 :type other: dict or FlatDict 86 return not self.
__eq__(other)
89 """Get an item for the specified key, automatically dealing with 92 :param mixed key: The key to use 103 """Iterate over the flat dictionary key and values 106 :raises: RuntimeError 109 return iter(self.
keys())
112 """Return the number of items. 117 return len(self.
keys())
120 """Return state information for pickling 128 """Return the string representation of the instance. 133 return '<{} id={} {}>"'.format(
134 self.__class__.__name__, id(self), str(self))
137 """Assign the value to the key, dynamically building nested 138 FlatDict items where appropriate. 140 :param mixed key: The key for the item 141 :param mixed value: The value for the item 145 if isinstance(value, self.
_COERCE)
and not isinstance(value, FlatDict):
146 value = self.__class__(value, self.
_delimiter)
152 elif not isinstance(self.
_values[pk], FlatDict):
154 'Assignment to invalid type for key {}'.format(pk))
160 """Return the string value of the instance. 165 return '{{{}}}'.format(
', '.join(
166 [
'{!r}: {!r}'.format(k, self[k])
for k
in self.
keys()]))
169 """Return the :class:`~flatdict.FlatDict` as a :class:`dict` 175 for key
in self.
keys():
180 if isinstance(self.
_values[pk], FlatDict)
and pk
not in out:
182 if isinstance(self.
_values[pk][ck], FlatDict):
185 out[pk][ck] = self.
_values[pk][ck]
191 """Remove all items from the flat dictionary.""" 195 """Return a shallow copy of the flat dictionary. 197 :rtype: flatdict.FlatDict 202 def get(self, key, d=None):
203 """Return the value for key if key is in the flat dictionary, else 204 default. If default is not given, it defaults to ``None``, so that this 205 method never raises :exc:`KeyError`. 207 :param mixed key: The key to get 208 :param mixed d: The default value 218 """Return a copy of the flat dictionary's list of ``(key, value)`` 221 .. note:: CPython implementation detail: Keys and values are listed in 222 an arbitrary order which is non-random, varies across Python 223 implementations, and depends on the flat dictionary's history of 224 insertions and deletions. 232 """Return an iterator over the flat dictionary's (key, value) pairs. 233 See the note for :meth:`flatdict.FlatDict.items`. 235 Using ``iteritems()`` while adding or deleting entries in the flat 236 dictionary may raise :exc:`RuntimeError` or fail to iterate over all 240 :raises: RuntimeError 243 for item
in self.
items():
247 """Iterate over the flat dictionary's keys. See the note for 248 :meth:`flatdict.FlatDict.items`. 250 Using ``iterkeys()`` while adding or deleting entries in the flat 251 dictionary may raise :exc:`RuntimeError` or fail to iterate over all 255 :raises: RuntimeError 258 for key
in self.
keys():
262 """Return an iterator over the flat dictionary's values. See the note 263 :meth:`flatdict.FlatDict.items`. 265 Using ``itervalues()`` while adding or deleting entries in the flat 266 dictionary may raise a :exc:`RuntimeError` or fail to iterate over all 270 :raises: RuntimeError 273 for value
in self.
values():
277 """Return a copy of the flat dictionary's list of keys. 278 See the note for :meth:`flatdict.FlatDict.items`. 285 if isinstance(value, (FlatDict, dict)):
286 nested = [self.
_delimiter.join([key, k])
for k
in value.keys()]
287 keys += nested
if nested
else [key]
292 def pop(self, key, default=NO_DEFAULT):
293 """If key is in the flat dictionary, remove it and return its value, 294 else return default. If default is not given and key is not in the 295 dictionary, :exc:`KeyError` is raised. 297 :param mixed key: The key name 298 :param mixed default: The default value 302 if key
not in self
and default != NO_DEFAULT:
309 """If key is in the flat dictionary, return its value. If not, 310 insert key with a value of default and return default. 311 default defaults to ``None``. 313 :param mixed key: The key name 314 :param mixed default: The default value 323 """Override the default or passed in delimiter with a new value. If 324 the requested delimiter already exists in a key, a :exc:`ValueError` 327 :param str delimiter: The delimiter to use 331 for key
in self.
keys():
333 raise ValueError(
'Key {!r} collides with delimiter {!r}', key,
337 if isinstance(self.
_values[key], FlatDict):
341 """Update the flat dictionary with the key/value pairs from other, 342 overwriting existing keys. 344 ``update()`` accepts either another flat dictionary object or an 345 iterable of key/value pairs (as tuples or other iterables of length 346 two). If keyword arguments are specified, the flat dictionary is then 347 updated with those key/value pairs: ``d.update(red=1, blue=2)``. 349 :param iterable other: Iterable of key, value pairs 356 """Return a copy of the flat dictionary's list of values. See the note 357 for :meth:`flatdict.FlatDict.items`. 365 """Checks to see if the key contains the delimiter. 370 return isinstance(key, basestring)
and self.
_delimiter in key
374 """Like :class:`~flatdict.FlatDict` but also coerces lists and sets 375 to child-dict instances with the offset as the key. Alternative to 376 the implementation added in v1.2 of FlatDict. 379 _COERCE = (list, tuple, set, dict, FlatDict)
380 _ARRAYS = (list, set, tuple)
385 value = dict([(str(i), v)
for i, v
in enumerate(value)])
386 super(FlatterDict, self).
__init__(value, delimiter)
389 """Assign the value to the key, dynamically building nested 390 FlatDict items where appropriate. 392 :param mixed key: The key for the item 393 :param mixed value: The value for the item 397 if isinstance(value, self.
_COERCE)
and \
398 not isinstance(value, FlatterDict):
399 value = self.__class__(value, self.
_delimiter)
406 'original_type',
None)
in self.
_ARRAYS:
411 'Assignment to invalid type for key {}{}{}'.format(
413 elif not isinstance(self.
_values[pk], FlatterDict):
415 'Assignment to invalid type for key {}'.format(pk))
421 """Return the :class:`~flatdict.FlatterDict` as a nested 428 for key
in self.
keys():
433 if isinstance(self.
_values[pk], FlatterDict)
and pk
not in out:
435 if isinstance(self.
_values[pk][ck], FlatterDict):
436 if self.
_values[pk][ck].original_type == tuple:
438 elif self.
_values[pk][ck].original_type == list:
440 elif self.
_values[pk][ck].original_type == set:
442 elif self.
_values[pk][ck].original_type == dict:
445 out[pk][ck] = self.
_values[pk][ck]
451 """Returns a list of values from the child FlatterDict instance 452 with string based integer keys. 454 :param str pk: The parent key 455 :param str ck: The child key 459 return [self.
_values[pk][ck][k]
461 key=
lambda x: int(x))]
def __init__(self, value=None, delimiter=':')
def update(self, other=None, kwargs)
def __setitem__(self, key, value)
def __init__(self, value=None, delimiter=':')
def setdefault(self, key, default)
def __contains__(self, key)
def set_delimiter(self, delimiter)
def get(self, key, d=None)
def __getitem__(self, key)
def pop(self, key, default=NO_DEFAULT)
def __delitem__(self, key)
def _has_delimiter(self, key)
def __setitem__(self, key, value)
def _child_as_list(self, pk, ck)