complicated dict comprehension - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: complicated dict comprehension (/thread-30650.html) |
complicated dict comprehension - rootVIII - Oct-29-2020 # Initial dictionary d = { 'one': 'some val', 'two': 'some val', 'three': { 'subkey_1': 'some val', 'subkey_2': 'some val' }, 'four': 'some val', 'five': { 'subkey_1': 'some val', 'subkey_2': 'some val' }, 'six': 'some val' } # This results in the dictionary that I want: new = {} for k, v in d.items(): if not isinstance(v, dict): new[k] = v else: for i, j in v.items(): new['%s_%s' % (k, i)] = j print(new) # example correct output: # { # 'one': 'some val', # 'two': 'some val', # 'three_subkey_1': 'some val', # 'three_subkey_2': 'some val', # 'four': 'some val', # 'five_subkey_1': 'some val', # 'five_subkey_2': 'some val', # 'six': 'some val' # } # But can this be done in a dict comprehension? # I am trying this: new = {k: v if not isinstance(v, dict) else {i['%s_%s' % (k, i)]: j for i, j in v.items()} for k, v in d.items()} print(new) # But I suspect that inner dictionary needs to be unpacked somehow? Is this possible? Maybe with another technique? RE: complicated dict comprehension - metulburr - Oct-29-2020 Quote:>>> import this RE: complicated dict comprehension - Gribouillis - Oct-29-2020 The first version is better. I like "yield" and reusable functions so I would write this d = { 'one': 'some val', 'two': 'some val', 'three': { 'subkey_1': 'some val', 'subkey_2': 'some val' }, 'four': 'some val', 'five': { 'subkey_1': 'some val', 'subkey_2': 'some val' }, 'six': 'some val' } def subitems(d): for key, value in d.items(): if isinstance(value, dict): for subkey, subvalue in value.items(): yield f"{key}_{subkey}", subvalue else: yield key, value new = dict(subitems(d)) print(new) RE: complicated dict comprehension - rootVIII - Oct-29-2020 Hmmm okay. I was wondering if possible to do the unreadable one-liner haha. Thanks RE: complicated dict comprehension - metulburr - Oct-29-2020 You can do pretty much anything in one liners. Especially list ocmps in combination with the use of the semicolon to separate statements on one line. But the time it takes to make them and decipher them is not worth the hassle. |