Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Functional Programming method of traversing a nested dictionary?

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 :)

like image 676
Ankit Solanki Avatar asked Dec 02 '13 09:12

Ankit Solanki


People also ask

How do you iterate over nested dictionaries?

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.

What is a nested dictionary explain with an example?

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.

How do you break a nested dictionary in Python?

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.

How do you make a nested dictionary dynamically in Python?

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.


1 Answers

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().

like image 165
Martijn Pieters Avatar answered Sep 21 '22 15:09

Martijn Pieters