Search code examples
pythonpython-3.xdictionarydictionary-comprehensioniterable-unpacking

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?

e.g.

{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}

Solution

  • 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 e.g.

    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