Hacker News new | ask | show | jobs
by abuckenheimer 2957 days 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
2 comments

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'])
Combining ideas from parent and grandparent:

  sum(planet.get('moons', 0) for planet in target['system']['planets'])
That's a great example! Mind if I use it? ;)
You can also use a list comprehension like so.

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