recursively traverse multidimensional dictionary, dimension unknown

Viewed 22205

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',
                },
            },
        },
    }
8 Answers

The solutions mentioned so far didn't do what I wanted but working from Justin Peel's spelled out version, I was able to make something that printed in a way I wanted:

def dict_parser(data, depth=0):
    if isinstance(data, dict):
        for key in data:
            value = data[key]
            print('  ') * depth + '"' + key + '":'
            dict_parser(value, depth + 1)
    elif isinstance(data, list):
        for item in data:
            if isinstance(item, list):
                dict_parser(item, depth + 1)
            else:
                print('  ') * depth + '"' + item + '"'
    elif isinstance(data, bool):
        print('  ') * depth + str(data)
    else:
        print('  ') * depth + '"' + data + '"'

Which printed something like:

"saved_skels":
  "E:\Child_Skeleton_6ft.fbx"
  "E:\Female_Skeleton_6ft.fbx"
  "E:\HeroFemale_Skeleton.fbx"
  "E:\HeroMale_Skeleton.fbx"
"saved_roots":
  "E:\users\Characters"
  "E:\content\characters"
"saved_tabs":
  "Characters":
    "ProxyFemale":
      "HeroFemale_Skeleton.fbx"
    "animation":
      "HeroFemale_Skeleton.fbx"
    "ProxyMale":
      "HeroMale_Skeleton.fbx"
  "Game":
    ""
  "Proto":
    "Female":
      "Female_Skeleton_NewBP.fbx"
  "Assets":
    ""
  "characters":
    "player":
      "player_Skeleton.fbx"
    "actor":
      "Hero_Skeleton.fbx"
"edit_common_checkbox_state":
  False
"get_latest_checkbox_state":
  True
Related