I am trying to find a better way to implement this:
d = {"a": {"b": {"c": 4}}}
l = ["a", "b", "c"]
for x in l:
d = d[x]
print (d) # 4
I am learning functional programming so I am just trying random example that come to my head :)
Iterate over all values of a nested dictionary in python We can achieve all this in a simple manner using recursion. Using the function nested_dict_pair_iterator() we iterated over all the values of a dictionary of dictionaries and printed each pair including the parent keys.
Nested Dictionary: Nesting Dictionary means putting a dictionary inside another dictionary. Nesting is of great use as the kind of information we can model in programs is expanded greatly.
Nested Dictionary Python: Delete Element To delete an item stored in a nested dictionary, we can use the del statement. The del statement lets you delete an object. del is written like a Python break statement , on its own line, followed by the item in the dictionary that you want to delete.
To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.
Use reduce()
:
reduce(dict.__getitem__, l, d)
or better still, using operator.getitem()
:
from operator import getitem
reduce(getitem, l, d)
Demo:
>>> d = {"a": {"b": {"c": 4}}}
>>> l = ["a", "b", "c"]
>>> from operator import getitem
>>> reduce(getitem, l, d)
4
Python 3 moved the reduce()
function out of the built-ins and into functools.reduce()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With