Reusing function results in Python dict

Viewed 98

I have the following (very simplified) dict. The get_details function is an API call that I would like to avoid doing twice.

ret = { 
    'a': a,
    'b': [{
        'c': item.c,
        'e': item.get_details()[0].e,
        'h': [func_h(detail) for detail in item.get_details()],
    } for item in items]
}

I could of course rewrite the code like this:

b = []
for item in items:
    details = item.get_details()
    b.append({
        'c': item.c,
        'e': details[0].e,
        'h': [func_h(detail) for detail in details],
    })

ret = { 
    'a': a,
    'b': b
}

but would like to use the first approach since it seems more pythonic.

3 Answers
Related