Python3 dictionary comprehension with sub-dictionary upacking?

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.


root



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






Resulting in what? what is your expected output?

– DeepSpace
Sep 6 '18 at 13:13






@DeepSpace updated to give clarity

– SumNeuron
Sep 6 '18 at 13:15






_k: _v for k,v in root.items() for _k, _v in (v if isinstance(v, dict) else k: v).items()

– Alexander McFarlane
Sep 6 '18 at 13:19


_k: _v for k,v in root.items() for _k, _v in (v if isinstance(v, dict) else k: v).items()






Possible duplicate of Nested dictionary comprehension python

– Alexander McFarlane
Sep 6 '18 at 13:21




3 Answers
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


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



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.


_flatten_into_kv_pairs


_flatten_into_kv_pairs


yield from


flatten_dict


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



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ