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:
for val in 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?"