Update a nested dictionary with values from another This is like dict.update except that it smoothly merges nested values This operates in-place and modifies old Parameters ---------- priority: string {'old', 'new', 'new-defaults'} If new (default) then the new diction
(
old: dict,
new: Mapping,
priority: Literal["old", "new", "new-defaults"] = "new",
defaults: Mapping | None = None,
)
| 81 | |
| 82 | |
| 83 | def update( |
| 84 | old: dict, |
| 85 | new: Mapping, |
| 86 | priority: Literal["old", "new", "new-defaults"] = "new", |
| 87 | defaults: Mapping | None = None, |
| 88 | ) -> dict: |
| 89 | """Update a nested dictionary with values from another |
| 90 | |
| 91 | This is like dict.update except that it smoothly merges nested values |
| 92 | |
| 93 | This operates in-place and modifies old |
| 94 | |
| 95 | Parameters |
| 96 | ---------- |
| 97 | priority: string {'old', 'new', 'new-defaults'} |
| 98 | If new (default) then the new dictionary has preference. |
| 99 | Otherwise the old dictionary does. |
| 100 | If 'new-defaults', a mapping should be given of the current defaults. |
| 101 | Only if a value in ``old`` matches the current default, it will be |
| 102 | updated with ``new``. |
| 103 | |
| 104 | Examples |
| 105 | -------- |
| 106 | >>> a = {'x': 1, 'y': {'a': 2}} |
| 107 | >>> b = {'x': 2, 'y': {'b': 3}} |
| 108 | >>> update(a, b) # doctest: +SKIP |
| 109 | {'x': 2, 'y': {'a': 2, 'b': 3}} |
| 110 | |
| 111 | >>> a = {'x': 1, 'y': {'a': 2}} |
| 112 | >>> b = {'x': 2, 'y': {'b': 3}} |
| 113 | >>> update(a, b, priority='old') # doctest: +SKIP |
| 114 | {'x': 1, 'y': {'a': 2, 'b': 3}} |
| 115 | |
| 116 | >>> d = {'x': 0, 'y': {'a': 2}} |
| 117 | >>> a = {'x': 1, 'y': {'a': 2}} |
| 118 | >>> b = {'x': 2, 'y': {'a': 3, 'b': 3}} |
| 119 | >>> update(a, b, priority='new-defaults', defaults=d) # doctest: +SKIP |
| 120 | {'x': 1, 'y': {'a': 3, 'b': 3}} |
| 121 | |
| 122 | See Also |
| 123 | -------- |
| 124 | dask.config.merge |
| 125 | """ |
| 126 | for k, v in new.items(): |
| 127 | k = canonical_name(k, old) |
| 128 | |
| 129 | if isinstance(v, Mapping): |
| 130 | if k not in old or old[k] is None or not isinstance(old[k], dict): |
| 131 | old[k] = {} |
| 132 | update( |
| 133 | old[k], |
| 134 | v, |
| 135 | priority=priority, |
| 136 | defaults=defaults.get(k) if defaults else None, |
| 137 | ) |
| 138 | elif ( |
| 139 | priority == "new" |
| 140 | or k not in old |
searching dependent graphs…