Python: Iterate over dict and list at the same time

dictionary, list, python

Solution

You need to call the `dict.items()` method:

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

otherwise you'll indeed get an exception telling you that the method itself isn't iterable:

>>> 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

That's because by not calling the method, you are trying to iterate over the method object, which doesn't support that operation.

Problem

I want to write a function that can iterate over `dict` and `list` in the same way, like the following code. However, it does not work and blames that `iter` is not iterator. ``` 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 + "," ``` Note: the inputs of this functions are either `dict` or `list`. This is an assumption. Here is the error msg: ``` File "./write-hole-collector.py", line 595, in constructResult for (key,value) in iter : TypeError: 'builtin_function_or_method' object is not iterable ```

Original source