'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 1:[1]

Im not sure if there is a shorter way of doing it, but Python is built to do one thing many different ways. Maybe this could be another way of doing it. I haven't tested it so it might not work.

def parse_data(key,value):
    iterator = isinstance(value,dict) 

    if iterator is False and 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 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1