0

I have a heavily nested dictionary with nested lists as well and I want to flatten it so that there's just one layer with appropriate subheadings. My code is below:

def flatten(d, parent_key='', sep='_',items=[]):

    if isinstance(d,list):
        d=d[0]

    if isinstance(d,dict):
        for child_key, v in d.items():
            new_key = parent_key + sep + child_key if parent_key else child_key
            items.append(new_key)
            flatten(v,new_key,sep,items)
    return items

#if the dictionary is:

x = {'patient': {'drug': [{'label': '1',
'substance': {'activesubstancename': 'ibuprofen'}}]}

#I would like to index like this:

x['patient_drug_label']
x['patient_drug_substance']
x['patient_drug_substance_activesubstancename']

#as opposed to:

x['patient]['drug'][0]['label'] etc.

The result I'm getting is expectedly a list of items with each element having the format of parent_key+'_'+child_key. But how can I take this a step further so I can actually flatten the dictionary and call these keys on the original dictionary.

AI92
  • 387
  • 1
  • 8

0 Answers0