Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:
    forvalin d['key2']:
        print("value:", val)

Solution 2:

Depends on what your goal is. You could do:

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

all_vals = []
for d in dicts:
    all_vals += d['key2']
print(", ".join(all_vals))

Post a Comment for "Are Nested Loops Required When Processing Json Response?"