Python:同时遍历dict和list

Python: Iterate over dict and list at the same time

我想写一个可以用同样的方式遍历dictlist的函数,就像下面的代码。但是,它不起作用并归咎于 iter 不是迭代器。

def constructResult(*args):
    header = ''
    result = ''
    for arg in args :
        if isinstance(arg, dict) :
            iter = arg.items; #arg is a dict
        else:
            iter = arg #arg is a list 
        for (key,value) in iter :
            header = header + key + ","

注意:此函数的输入为 dictlist。这是一个假设。

这是错误消息:

 File "./write-hole-collector.py", line 595, in constructResult
   for (key,value) in iter :
 TypeError: 'builtin_function_or_method' object is not iterable

您需要调用 dict.items() 方法:

iter = arg.items()  #arg is a dict

否则你确实会得到一个异常,告诉你方法本身是不可迭代的:

>>> d = {}
>>> for key, value in d.items:  # not called
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not iterable

那是因为通过不调用该方法,您正在尝试迭代不支持该操作的方法对象。

for key in z.keys(): print(key)

非变量函数的迭代器。尝试使用 keys()

而不是 Keys