7 ms·
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 ta
by abuckenheimer 8y 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
- mhashemi 8y agoThat's a great example! Mind if I use it? ;)
- ziikutv 8y agoYou can also use a list comprehension like so. >>> sum([x['moons'] for x in target['system']['planets']])
- jeremiahwv 8y agoFor 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 8y agoCombining ideas from parent and grandparent: sum(planet.get('moons', 0) for planet in target['system']['planets'])