Search code examples
pythonnested-loops

Are nested loops required when processing JSON response?


I have a list of dictionaries (JSON response). Each dictionary contains a key-value pairs with a list of strings. I'm processing these strings using a nested for-loop, which works fine.

However, I wondered if it is possible to collapse the two for-loops into a single loop using the product method. Obviously I cannot use the loop-variable a in the range function because it's not defined yet.

Is there a way to do this without iterating over the data multiple times?

from itertools import product

dicts = [
    {
        'key1': 'value1',
        'key2': ['value2', 'value3']
    },
    {
        'key1': 'value4',
        'key2': ['value5']
    }
]

count = len(dicts)
for a in range(count):
    for b in range(len(dicts[a]["key2"])):
        print "values: ", dicts[a]["key2"][b]

for a, b in product(range(count), range(len(dicts[a]["key2"]))):
    print("values: ", dicts[a]["key2"][b])

Solution

  • While you could collapse this into one loop, it's not worth it:

    from itertools import chain
    from operator import itemgetter
    
    for val in chain.from_iterable(map(itemgetter('key2'), dicts)):
        print("value:", val)
    

    It's more readable to just keep the nested loops and drop the awkward range-len:

    for d in dicts:
        for val in d['key2']:
            print("value:", val)