[Python] How to Get the Keys for A Dict (Dictionary) with Embedded Items (i.e. Dict inside Dict)

UPDATE: I realised that I had dictionaries inside dictionaries inside dictionaries, so needed something recursive (otherwise the code gets really ugly and messy.) The below was fine (okay) where you just have like one level of embedding (level 1 keys and level 2 keys.) For the cool recursive function I came up with, you'll have to check out: Python Dictionary Variable Recursive Explorer (cosonok.com)

I was interested in inspecting all the keys (and values) in a dictionary item I had as output from an application. I knew there were embedded items (i.e. dictionary items inside my dictionary) and I want to find out about these.

In the simple Python below:

  • d is my dictionary item

If your dictionary item is not d but say s[0] for example, you can simply do:

d = s[0]


The Python

# Level_1_Key = VALUE
# Level_1_Key.Level_2_Key = VALUE

for k in list(d.keys()):
 try:
  n = d[k].keys()
  for k2 in list(n):
   if d[k] == None:
    print(k + "." + k2)
   else:
    print(k + "." + k2 + " = " + d[k][k2])
 except:
  try:
   print(k + " = " + d[k]) 
  except:
   print(k+ " = None (NoneType)")


Comments