0

I have a python dictionary like following:

score_dictionary={'Agriculture':89,'Health':{'Public':90,'Private':78},'Mines':70,'Commerce':67}

Using this dictionary, I want to convert to the following:

score_dictionary={'Agriculture':89,'Health_public':90,'Health_Private':78,'Mines':70,'Commerce':67}

Now I'm stuck at how to convert it?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

4

You could use isinstance to check whether or not the value in a given key/value pair consist in another dictionary, format the key name with string formatting and update accordingly:

d = {}
for k,v in score_dictionary.items():
    if not isinstance(v, dict):
        d[k] = v
    else:
        for k_, v_ in v.items():
            d[f'{k}_{k_}'] = v_

print(d)

{'Agriculture': 89,
 'Health_Public': 90,
 'Health_Private': 78,
 'Mines': 70,
 'Commerce': 67}
yatu
  • 86,083
  • 12
  • 84
  • 139
  • 1
    Can you pls explain `d[f'{k}_{k_}'] = v_` code ? what does it mean by f ? – Moon Oct 18 '19 at 10:08
  • 2
    These are `f-strings`, the new syntax for string formatting, check https://www.python.org/dev/peps/pep-0498/ @moon – yatu Oct 18 '19 at 10:08
  • 1
    `f'stringhere'` is newer form of string-formatting. You could do the same thing with the following code: `d['{}_{}'.format(k, k_)] = v` – Hampus Larsson Oct 18 '19 at 10:09