python - Pythonic way to create dictionary from bottom level of nested dictionary -


i have dictionary contains nested dictionaries, this:

example_dict = {                 "test1": "string here",                 "test2": "another string",                 "test3": {                         "test4": 25,                         "test5": {                                   "test7": "very nested."                         },                         "test6": "yep, string"                 }, } 

assuming keys nested within unique, there pythonic way take dictionary , obtain 'bottom' level of keys , values?

by mean going recursive dictionary , obtaining key:value pairs value isn't dictionary (but still capturing key:value pairs within fulfil critera)? above following returned:

resulting_dict = {                 "test1": "string here",                 "test2": "another string",                 "test4": 25,                 "test7": "very nested.",                 "test6": "yep, string" } 

with bit of recursion it's simple do:

example_dict = {     "test1": "string here",     "test2": "another string",     "test3": {         "test4": 25,         "test5": {             "test7": "very nested."         },         "test6": "yep, string"     }, }   def flatten(dictionary):     output = dict()     k, v in dictionary.items():         if isinstance(v, dict):             output.update(flatten(v))         else:             output[k] = v      return output  resulting_dict = flatten(example_dict) 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -