Update value of a nested dictionary of varying depth
@FM's answer has the right general idea, i.e. a recursive solution, but somewhat peculiar coding and at least one bug. I'd recommend, instead:
Python 2:
import collections
def update(d, u):
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
d[k] = update(d.get(k, {}), v)
else:
d[k] = v
return d
Python 3:
import collections.abc
def update(d, u):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = update(d.get(k, {}), v)
else:
d[k] = v
return d
The bug shows up when the "update" has a k
, v
item where v
is a dict
and k
is not originally a key in the dictionary being updated -- @FM's code "skips" this part of the update (because it performs it on an empty new dict
which isn't saved or returned anywhere, just lost when the recursive call returns).
My other changes are minor: there is no reason for the if
/else
construct when .get
does the same job faster and cleaner, and isinstance
is best applied to abstract base classes (not concrete ones) for generality.
Update nested dictionary value with same key's value one level up
Looks like you need
>>> d[0]['bb']['z'] = d[0]['z']
If you want to do this for every subkey, then try a dict comprehension
>>> {k:v if not isinstance(v, dict)
else {subkey: (subval if subkey not in d[0] else d[0][subkey])
for (subkey, subval) in v.items()}
for k,v in d[0].items()}
varying depth nested dict from list of tuples
You can use recursion:
reform_list = [('a','b','c',[1,2,3]),('d','e','f','g',[4,5,6])]
my_map = [2,1,0,3]
def build_dict(mp, val):
if not mp or len(val) - 1 <= mp[0]:
return val[-1]
return {val[mp[0]]:build_dict(mp[1:],val)}
results = [build_dict(my_map, i) for i in reform_list]
Output:
[{'c': {'b': {'a': [1, 2, 3]}}}, {'f': {'e': {'d': {'g': [4, 5, 6]}}}}]
Python: Updating a value in a deeply nested dictionary
multi_match = query['query']['function_score']['query']['multi_match']
multi_match['operator'] = 'or'
multi_match.update({'minimum_should_match' : '80%' })
Related Topics
How to Extract the Decision Rules from Scikit-Learn Decision-Tree
How to Get the Named Parameters from a Url Using Flask
How to Avoid Circular Imports in Python
Python Beautifulsoup Parsing Table
I'm Getting Key Error in Python
How to Read Text from the Clipboard
Difference Between Class and Instance Methods
How to Handle the Window Close Event in Tkinter
Find Common Substring Between Two Strings
What Does 'Weight' Do in Tkinter
Groupby Results to Dictionary of Lists
Item Frequency Count in Python
Modifying a Python Dict While Iterating Over It
Why Does Checking a Variable Against Multiple Values with 'Or' Only Check the First Value