python - How to recursively flatten a nested dictionary? -


thought had simple solution problem turns out off.

i have nested dictionary:

my_dict = { "username": "myemail@email.com",   "name": { "first": "john", "last": "doe" },   "occupation": "web developer" } 

i wrote recursive function unwrap existing dictionary:

def adder(my_dict, existing_dict):     k, v in my_dict:         if not isinstance(v, dict):             existing_dict[k] = v         else:             adder(v.iteritems(), existing_dict)     return existing_dict   existing_dict = { "role": "employee" } adder(my_dict.iteritems(), existing_dict) 

stepping through loop, goes until hit recursion, my_dict goes dictionary dictionary-itemiterator object @ 0x07f6750086c00.

i don't see obvious errors, although seemingly v.iteritems() breaks (and yet loop finishes). ideas?

i agree above - iterating on dict iterates on keys.

additionally, think want return existing_dict function, my_dict unmodified. also, want pass dict function, not iterator.

def adder(my_dict, existing_dict):     k, v in my_dict.iteritems():         if not isinstance(v, dict):             existing_dict[k] = v         else:             adder(v, existing_dict)     return existing_dict  in [47]: adder(my_dict, existing_dict) out[47]:  {'first': 'john',  'last': 'doe',  'occupation': 'web developer',  'role': 'employee',  'username': 'myemail@email.com'} 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -