k3dict
Dict operation utilities including iteration, getter/setter makers, and attribute access.
k3dict is a component of pykit3 project: a python3 toolkit set.
Installation
pip install k3dict
Quick Start
import k3dict
mydict = {'a':
{'a.a': 'v-a.a',
'a.b': {'a.b.a': 'v-a.b.a'},
'a.c': {'a.c.a': {'a.c.a.a': 'v-a.c.a.a'}}
}
}
# depth-first iterate the dict
for rst in k3dict.depth_iter(mydict):
print(rst)
# output:
# (['a', 'a.c', 'a.c.a', 'a.c.a.a'], 'v-a.c.a.a')
# (['a', 'a.b', 'a.b.a'], 'v-a.b.a')
# (['a', 'a.a'], 'v-a.a')
# breadth-first iterate the dict
for rst in k3dict.breadth_iter(mydict):
print(rst)
API Reference
k3dict
k3dict
It provides with several dict operation functions.
Status
This library is considered production ready.
AttrDict
Bases: dict
a = AttrDict({1:2}) # {1:2} a = AttrDict(x=3) # {"x":3} a.x # 3 a['x'] # 3
Some pros:
- It actually works!
- No dictionary class methods are shadowed (e.g. .keys() work just fine)
- Attributes and items are always in sync
- Trying to access non-existent key as an attribute correctly raises AttributeError instead of KeyError
Cons:
- Methods like .keys() will not work just fine if they get overwritten by incoming data
- Causes a memory leak in Python < 2.7.4 / Python3 < 3.2.3
- Pylint goes bananas with E1123(unexpected-keyword-arg) and E1103(maybe-no-member)
- For the uninitiated it seems like pure magic.
Issues:
- Dictionary key overrides dictionary methods:
d = AttrDict() d.update({'items':["a", "b"]}) d.items() # TypeError: 'list' object is not callable
Source code in k3dict/dictutil.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
FixedKeysDict
Bases: dict
It provides the base class for dict with explicit keys.
:param args: as builtin dict. :param argkv: as builtin dict. :return: An instance of dictutil.FixedKeysDict.
Source code in k3dict/fixed_keys_dict.py
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
attrdict(*args, **kwargs)
Make a dict-like object whose keys can also be accessed with attribute. You can use an AttrDict instance just like using a dict instance.
Source code in k3dict/dictutil.py
376 377 378 379 380 381 382 383 | |
attrdict_copy(*args, **kwargs)
Same as dictutil.attrdict, except that:
every time to access it by an attribute or by a key, the value is copied before returning.
It does not allow to set its attribute or key, such as a["x"]=1 or a.x=1.
Source code in k3dict/dictutil.py
386 387 388 389 390 391 392 393 | |
breadth_iter(mydict)
:param mydict: the dict you want to iterative :return: an iterator, each element it yields is a tuple that contains keys and value.
Source code in k3dict/dictutil.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
combineto(a, b, op, exclude=None, recursive=True)
:param a: the dict to combine to, must be a dict.
:param b: the dict to combine with, if it is not a dict, it will be ignored.
:param op: the operation to take when combining common keys, such as operator.add.
:param exclude: a dict used to specify keys than should not be combined
if exclude = {'k1': {'k2': True}}, then b['k1']['k2'] will be ignored
if exclude = {'k1': True}, then b['k1'] will be ignored totally.
:param recursive: a bool value, if set to False, will not dive into sub dict.
:return: the combined dict.
Source code in k3dict/dictutil.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
depth_iter(mydict, ks=None, maxdepth=10240, intermediate=False, empty_leaf=False, is_allowed=None)
mydict: the dict that you want to iterate on.
ks: the argument could be a list, it would be seted ahead of key's list in
results of iteration
maxdepth: specifies the max depth of iteration.
intermediate: if it is True, the method will show the intermediate key path those
points to a non-leaf descendent.
By default it is False.
empty_leaf:treat empty dict as a leaf node.
By default it is False, thus only non-dict elements are yielded.
is_allowed:specifies a user - customized callable to choose what keys and value to
yield.
If is_allowed is specified, intermediate and empty_leaf are ignored
for dict value.
It accepts two argument keys and value.
It should return True or False.
By defaul it is None.
:return: an iterator. Each element it yields is a tuple of keys and value.
Source code in k3dict/dictutil.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
get(dic, key_path, vars=None, default=0, ignore_vars_key_error=None)
Returns the value of the item specified by key_path.
:param dic: dictionary.
:param key_path: can be string , tuple or list.
:param vars: is a dictionary contains dynamic keys in key_path.
:param default: is the default value if the item is not found.
For example when foo.bar is used on a dictionary {"foo":{}}.
:param ignore_vars_key_error: specifies if it should ignore when a dynamic key does not present in vars.
:return: item value it found by key_path, or default
Source code in k3dict/dictutil.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
make_getter(key_path, default=0)
It creates a lambda that returns the value of the item specified by
:param key_path: can be string , tuple or list.
:param default: is the default value if the item is not found.
For example when foo.bar is used on a dictionary {"foo":{}}.
It must be a primitive value such as int, float, bool, string or None.
:return: the item value found by key_path, or the default value if not found.
Source code in k3dict/dictutil.py
188 189 190 191 192 193 194 195 196 197 | |
make_setter(key_path, value=None, incr=False)
It creates a function setter(dic, value=None, vars={}) that can be used to
set(or increment) the item value specified by key_path in a dictionary dic.
:param key_path: can be string , tuple or list.
:param value: is the value to use if setter is called with its own value set to None.
:param incr: specifies whether the value should be overwritten(incr=False) or
added to present value(incr=True).
:return: a function setter(dic, value=None, vars={}) that can be used to set an item
value in a dictionary to value(or to the value that is passed tomake_setter,
if the value passed to setter is None).
vars is a dictionary that contains dynamic item keys.
setter returns the result value.
Source code in k3dict/dictutil.py
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
subdict(source, flds, use_default=False, default=None, deepcopy=False, deepcopy_default=False)
Make a new dict as a subdict of source, whose keys are in flds, and values are from source.
:param source: is a dict, to get subdict from.
:param flds: are keys wanted to copy to subdict. An iterable that can be used with for-in statement.
:param use_default: is a boolean. If use_default is True, use default value for those keys in flds but not
in source, otherwise, those keys will not exist in result.By default, it is False.
:param default: offers a default value for those keys in flds but not in source. If it is callable, it will
be called with a key in flds as input to return a default value for that key in subdict.
:param deepcopy: is a boolean. If it is True, use copy.deepcopy to copy value to new dict. By default,
it is False.
:param deepcopy_default: is a boolean. If it is True, use copy.deepcopy to copy default to new dict.
By default, it is False.
:return: a dict.
Source code in k3dict/dictutil.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | |
License
The MIT License (MIT) - Copyright (c) 2015 Zhang Yanpo (张炎泼)