简体   繁体   中英

How to optimize the code with try/except block?

I have function like:

def get_nested_dicts(items: dict, *keys, default=None):
    for key in keys:
        try:
            items = items[key]
        except KeyError:
            return default
        else:
            if not isinstance(items, dict):
                break

    return items

The main idea is optimizing work with nested dictionaries, for example, I have constraction like:

dictionary = {'a': {'b': {'c': 10}}}

Output will be like:

print(get_nested_dicts(items, 'a', 'b', 'c')) # 10 
print(get_nested_dicts(items, 'a', 'c', 'b')) # None
print(get_nested_dicts(items, 'd', 'e', 'g')) # None

And want to optimize it more, make in more pythonic way. Are there some solutions to optimize it?

You can use dict.get() as follows:

def get_nested_dicts(items: dict, *keys, default=None):
    for key in keys:
        items = items.get(key, default)
        if not isinstance(items, dict):
            break

    return items

Input

dictionary = {'a': {'b': {'c': 10}}}

print(get_nested_dicts(dictionary, 'a', 'b', 'c')) 
print(get_nested_dicts(dictionary, 'a', 'c', 'b')) 
print(get_nested_dicts(dictionary, 'd', 'e', 'g')) 

Output

10
None
None

Here get() takes two arguments the key and the default value to return. Here it returns the value corresponding to the key if key is present in the dictionary else None is returned.

I guess, .get() function will help you optimize this a little bit.

def get_nested_dicts(items: dict, *keys, default=None):
    for key in keys:
        items = items.get(key, default)
        if not isinstance(items, dict): break
    return items

Another pythonic way is to use the wildcard - 'reduce'.

from functools import reduce

def get_nested_dicts(items: dict, *keys, default=None):
    return reduce(lambda v, k: v.get(k, default) if v else default, keys, items)
    

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM