I want to create a function to recursively traverse a multidimensional dictionary, where the dimensions are unknown.
Here is what I have come up with so far, but it doesn’t seem to be working correctly. This will print out some key / values twice and they are not in order.
def walk_dict(d):
for k,v in d.items():
if isinstance(v, dict):
walk_dict(v)
else:
print "%s %s" % (k, v)
Here’s a sample array:
d = {
'plan_code': 'b',
'quantity': '1',
'account': {
'account_code': 'b',
'username': 'jdoe',
'email': 'jdoe@domain.com',
'first_name': 'b',
'last_name': 'b',
'company_name': 'Company, LLC.',
'billing_info': {
'first_name': 'b',
'last_name': 'b',
'address1': '123 Test St',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
'zip': '94105',
'credit_card': {
'number': '1',
'year': '2018',
'month': '12',
'verification_value': '123',
},
},
},
}
I’m not sure what your ultimate goal is, but the code is doing what it is supposed to. You are seeing what you think are repeats of items because there are key/value combos like ‘first_name’:’b’ that are both within ‘account’ and within ‘billing_info’ within ‘account’. I’m not sure what order you are looking for, but dictionaries are unordered so your function to print them out will have to give them some order, for instance by replacing the following:
with
or you’ll need an ordered dictionary. You can also use the pprint module like so to give a nice print out of a dict:
However, I’m not fully sure what your end goal is here. Also, you are missing the keys when the values are dictionaries. I modified your code to do a similar thing to what pprint does in the following:
which for your example dict yields: