28 Dec 2014

A generic method for python nested dictionary

In recent project i was working to integrate the third party library. In response to call i have a json object which holds the data of all the trips. It was a list of dictionaries, each dictionary holding the data about a trip and it was a nested dictionary.

Now situation was at different part of the code has to look out the trip dictionary for given key(s). So i wrote a generic method which will take the key and results the value of that key.  

Following is a simplification of scenario as i described above. 

Here is a python nested dictionary,
dic = {"a": 1, {"b": {"c": 2}}.

Now have generic method which operates on this dictionary, and this method can be called from different places of the program passing key of dictionary.
def get_value(dic, key):
      # return value of key

In gerenal one can get the value from dictionary like:
dic['a']   ---> 1

If i had to fetch the value of 2 from dic , it is quite simple.
dic['b']['c']  ---> 2

Since it is a nested dictionary, how get_value function is to return 2 ?
Here the reduce function comes to help:
reduce(dic.get, ['b', 'c'], dic) 

What it does is,
dic.get('b')  ---> {'c': 2},     #now dic is updated to {'c': 2}
dic.get('c')  ----> 2 

Using reduce helped me to wrote the generic method which can be operated on any python dictionary.

Thanks falsetru helped me to understand this.



No comments:

Post a Comment