Search code examples
pythoniteratorpython-3.x

Iterator for both lists and dictionaries


I have a parameter dictionary holding complex data composed of strings, lists and other dictionaries. Now I want to iterate through this data.

My problem is the way - the best practice - for having an iterator, which iterates both lists and dictionaries.

What I have:

def parse_data(key, value):
    iterator = None

    if isinstance(value, dict):
        iterator = value.items()
    elif isinstance(value, list):
        iterator = enumerate(value)

    if iterator is not None:
        for key, item in iterator:
            parse_data(key, item)
        return

    # do some cool stuff with the rest

This does not look very pythonish. I thought of a function similar to iter giving me the possibilty to iterate over both key and item.


Solution

  • I think this i quite pythonic. I would just change it to:

    def parse_data:
    
        if isinstance(value, dict):
            iterator = value.items()
        elif isinstance(value, list):
            iterator = enumerate(value)
        else:
            return
    
        for key, item in iterator:
            parse_data(value, key, item)
    
        # do some cool stuff with the rest