Oct-29-2020, 07:02 PM
# 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?