简体   繁体   中英

Python How to access by keys when iterating a dictionary returns tuple

Iterating over a dictionary returns a tuple. Then how can the elements be accessed with key if the iteration retunes a tuple? I am expecting the iteration to give the nested dictionary so I can traverse further and access items with keys. With tuple returned I can't.

>>> d = { 'f': { 'f1': { 'f11':''}, }, 's': {  }}
>>> d
{'f': {'f1': {'f11': ''}}, 's': {}}
>>> for p in d.items():
...                 print(type(p))
...                 print(p['f1'])
...
<class 'tuple'>
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: tuple indices must be integers or slices, not str

It is probably easiest if you unpack the tuple in the for loop:

for key, val in d.items():
    print(key, val)

Here's a worked-out example of how to unpack the tuple and how to make recursive calls:

>>> def list_recursive(d):
        for key, value in d.items():
            print('Key:', key)
            print('Value:', value)
            print()
            if isinstance(value, dict):
                list_recursive(value)

>>> d = { 'f': { 'f1': { 'f11':''}, }, 's': {  }}
>>> list_recursive(d)
Key: f
Value: {'f1': {'f11': ''}}

Key: f1
Value: {'f11': ''}

Key: f11
Value: 

Key: s
Value: {}

If you want to iterate through nested dictionaries of unknown length try this. Recursion is the best way.

def recur(d):
    for key,val in d.items():
        print(key,val)
        if isinstance(val,dict):
            recur(val)

d={ 'f': { 'f1': { 'f11':''}, }, 's': {  }}
recur(d)

f {'f1': {'f11': ''}}
f1 {'f11': ''}
f11 
s {}

Try traversing like this:

for p in d:
    print(type(d[p]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM