top | item 17033834

(no title)

abuckenheimer | 7 years ago

I feel the same way, although my instinct is generally to build a custom generator. Only costs a couple lines but is plain old python and quite explicit

    target = {'system': {'planets': [{'name': 'earth', 'moons': 1},
                                     {'name': 'jupiter', 'moons': 69}]}}

    glom(target, {'moon_count': ('system.planets', ['moons'], sum)})
    # vs
    def iter_moons(t):
        for planet in target['system']['planets']:
            yield planet['moons']

    sum(iter_moons(target))
would have to combine with `defaultdict`s if your nested data is only sometimes there though

discuss

order

jeremiahwv|7 years ago

For simple cases like this it doesn't even cost a couple lines as sum() can take a generator expression:

  sum(planet['moons'] for planet in target['system']['planets'])

divbzero|7 years ago

Combining ideas from parent and grandparent:

  sum(planet.get('moons', 0) for planet in target['system']['planets'])

mhashemi|7 years ago

That's a great example! Mind if I use it? ;)

ziikutv|7 years ago

You can also use a list comprehension like so.

>>> sum([x['moons'] for x in target['system']['planets']])