Search code examples
pythonlistloopsdictionarytraversal

Python: How to traverse a List[Dict{List[Dict{}]}]


I was just wondering if there is a simple way to do this. I have a particular structure that is parsed from a file and the output is a list of a dict of a list of a dict. Currently, I just have a bit of code that looks something like this:

for i in xrange(len(data)):
    for j, k in data[i].iteritems():
        for l in xrange(len(data[i]['data'])):
            for m, n in data[i]['data'][l].iteritems():
                dostuff()

I just wanted to know if there was a function that would traverse a structure and internally figure out whether each entry was a list or a dict and if it is a dict, traverse into that dict and so on. I've only been using Python for about a month or so, so I am by no means an expert or even an intermediate user of the language. Thanks in advance for the answers.

EDIT: Even if it's possible to simplify my code at all, it would help.


Solution

  • You never need to iterate through xrange(len(data)). You iterate either through data (for a list) or data.items() (or values()) (for a dict).

    Your code should look like this:

    for elem in data:
        for val in elem.itervalues():
            for item in val['data']:
    

    which is quite a bit shorter.