简体   繁体   中英

Python3 dictionary comprehension with sub-dictionary upacking?

Suppose one has a dictionary, root which consists of key:value pairs, where some values are themselves dictionaries.

Can one (and if so, how) unpack these sub dictionaries via dictionary comprehension?

eg

{k: v if type(v) is not dict else **v for k, v in root.items()}

example:

root = {'a': 1, 'b': {'c': 2, 'd': 3}}


result = {'a': 1, 'c': 2, 'd': 3}

I guess I should post as an answer with a more broad explanation to help you as it is a little bit different to other existing questions

{
    _k: _v
    for k, v in root.items()
    for _k, _v in (         # here I create a dummy dictionary if non exists
                      v if isinstance(v, dict) else {k: v}
                  ).items() # and iterate that
}

The key part of understanding is that you need consistent and generic logic for the comprehension to work.

You can do this by creating dummy nested dictionaries where they don't previously exist using v if isinstance(v, dict) else {k: v}

Then this is a simple nested dictionary unpacking exercise.

To help in your future comprehensions I would recommend writing the code out eg

res = dict()
for k,v in root.items():
    d = v if isinstance(v, dict) else {k: v}
    for _k, _v in d.items():
        res[_k] = _v

and work backwards from this

Useful references

If you have several levels of nested dictionaries, I suggest you the following solution based on a recursive function:

def flatten(res, root):
    for k,v in root.items():
        if isinstance(v, dict):
            flatten(res, v)
        else:
            res[k] = v

root = {'a': 1, 'b': {'c': 2, 'd': {'e': 5, 'f': 6}}}

result = {}
flatten(result, root)

print(result)  # {'a': 1, 'c': 2, 'e': 5, 'f': 6}

Here is a recursive solution. In the function _flatten_into_kv_pairs , we iterate through the key and values pair and yield those keys/values if the value is a not a dictionary. If it is, then we recursively call _flatten_into_kv_pairs with the yield from construct. The function flatten_dict is just a shell which turns sequence of key/value pairs back into a dictionary.

def _flatten_into_kv_pairs(dict_object):
    for k, v in dict_object.items():
        if isinstance(v, dict):
            yield from _flatten_into_kv_pairs(v)
        else:
            yield k, v


def flatten_dict(dict_object):
    return dict(_flatten_into_kv_pairs(dict_object))


root = {'a': 1, 'b': {'c': 2, 'd': 3, 'e': {'f': 4, 'g': 5}}}
print(flatten_dict(root))

Output:

{'a': 1, 'c': 2, 'd': 3, 'f': 4, 'g': 5}

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