1

I have a dict of nested dicts and key-values.

 dicta = {'key1': {'keya': 'a', 'keyb': 'b'},
      'key2': {'key3':{'keyc': 'c'}}, 'key4': 4}}

Is there a way I can use a for loop to get to 'c'?

I tried,

print(dicta['key2'])

for x in dicta['key2']:
    for y in x['key3']:
        print(y)

For the first print, I get

{'key3': {'keyc': 'c'}}

But I get TypeError: string indices must be integers for the second print.

Thanks in advance! *I edited replacing n with dicta; I copied and pasted it wrong the first time.

codeforester
  • 39,467
  • 16
  • 112
  • 140
user7552322
  • 15
  • 1
  • 5

5 Answers5

1

In general, no. Dicts can be arbitrarily recursively deep, and there's no good way to traverse them using nothing but a for loop. (You could implement your own stack using a list and simulate recursion, but that's not "good".)

There's some recursive code for traversing dictionaries (counting the depth) in this question.

In specific, sure. Knowing the structure in advance, you can use the right number of for loops:

n = {'key1': {'keya': 'a', 'keyb': 'b'},
     'key2': {'key3':{'keyc': 'c'}}, 'key4': 4}

for k1,v1 in n.items():
    try:
        for k2,v2 in v1.items():
            try:
                for k3,v3 in v2.items():
                    print(v3)
            except AttributeError:
                pass
    except AttributeError:
        pass
Community
  • 1
  • 1
aghast
  • 14,785
  • 3
  • 24
  • 56
1

for i in somedict is to loop all the keys from a dictionary. See more details from dict views

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

items() returns a new view of the dictionary’s items ((key, value) pairs). So you can just try this:

for k,v in dicta['key2'].items():
    if isinstance(v,dict):
        for k1,v1 in v.items():
            print(v1)

isinstance(v,dict) return true if the object argument is an instance of the dict argument,so you don't need to catch exception.

Have a look at looping-techniques

Hope this helps.

McGrady
  • 10,869
  • 13
  • 47
  • 69
0

You can use recursion to dive into given dictionary and print the key and its values.

def drill(dicta):
  for k in dicta.keys():
    if isinstance(dicta[k],dict):
      drill(dicta[k])
    else:
      print ('dicta[',k,']=',dicta[k])
  return
Samiie
  • 124
  • 4
0
for k in n:
    v = n.get(k)
    if isinstance(v, dict):
    for j in v:
        print(v.get(j))
Naser Hamidi
  • 176
  • 1
  • 11
0

Using nested loop you can get the required results.

for k,v in dicta.items():
     if k=="key2":
         new_dict=v
         for k1, v1 in new_dict.items():
               print v1["keyc"]
Aashutosh jha
  • 552
  • 6
  • 8
  • Welcome to Stack Overflow! While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem. – Joe C Feb 12 '17 at 09:40