[英]Python How to access by keys when iterating a dictionary returns tuple
迭代字典返回一个元组。 那么如果迭代重新调整元组,如何使用key
访问元素? 我期待迭代提供嵌套字典,以便我可以进一步遍历并使用键访问项目。 随着元组返回我不能。
>>> 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
如果在 for 循环中解压元组,这可能是最简单的:
for key, val in d.items():
print(key, val)
这是一个如何解包元组以及如何进行递归调用的示例:
>>> 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: {}
如果你想遍历未知长度的嵌套字典,试试这个。 递归是最好的方法。
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 {}
尝试像这样遍历:
for p in d:
print(type(d[p]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.