How to recursively flatten a nested dictionary?
dictionary, python, python-2.7, recursion
Solution
I agree with the above - iterating on the just the dict itself only iterates on the keys.
Additionally, I think you want to return existing_dict from the function, my_dict is unmodified. Also, you want to pass the dict back into the function, not the iterator.
def adder(my_dict, existing_dict):
for 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'}
Problem
Thought I had a simple solution for this problem but it turns out I was off. I have a nested dictionary: ``` my_dict = { "username": "myEmail@email.com", "name": { "first": "John", "last": "Doe" }, "occupation": "Web Developer" } ``` I wrote a recursive function to unwrap it into an existing dictionary: ``` def adder(my_dict, existing_dict): for 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 the loop, everything goes well until I hit the recursion, then `my_dict` goes from the dictionary to `dictionary-itemiterator object at 0x07f6750086c00`. I don't see any obvious errors, although seemingly `v.iteritems()` breaks everything (and yet the loop finishes). Any ideas?