What is the best way to implement nested dictionaries?

后端 未结 21 1814
[愿得一人]
[愿得一人] 2020-11-22 00:29

I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:

{\'new jersey\': {\'mercer county\': {\'plumbers\':          


        
21条回答
  •  情歌与酒
    2020-11-22 00:34

    I used to use this function. its safe, quick, easily maintainable.

    def deep_get(dictionary, keys, default=None):
        return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
    

    Example :

    >>> from functools import reduce
    >>> def deep_get(dictionary, keys, default=None):
    ...     return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
    ...
    >>> person = {'person':{'name':{'first':'John'}}}
    >>> print (deep_get(person, "person.name.first"))
    John
    >>> print (deep_get(person, "person.name.lastname"))
    None
    >>> print (deep_get(person, "person.name.lastname", default="No lastname"))
    No lastname
    >>>
    

提交回复
热议问题