Python Forum
complicated dict comprehension
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
complicated dict comprehension
#1
# 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?
Reply


Messages In This Thread
complicated dict comprehension - by rootVIII - Oct-29-2020, 07:02 PM
RE: complicated dict comprehension - by metulburr - Oct-29-2020, 07:31 PM
RE: complicated dict comprehension - by Gribouillis - Oct-29-2020, 08:07 PM
RE: complicated dict comprehension - by rootVIII - Oct-29-2020, 08:54 PM
RE: complicated dict comprehension - by metulburr - Oct-29-2020, 10:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Complicated ComputerAstronaut 1 1,639 Dec-10-2020, 03:19 AM
Last Post: DT2000
  a complicated randomized function which I'm stuck on jojo77m 11 3,687 Aug-27-2020, 09:24 AM
Last Post: DPaul
  dictionary: print key/value with list(dict) comprehension wardancer84 4 3,031 Nov-14-2018, 03:14 PM
Last Post: wardancer84
  Newbie question for complicated namedtuple generation zydjohn 0 2,209 Dec-16-2017, 09:50 AM
Last Post: zydjohn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020