Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

reduce list of dictionaries

  • Combining map and filter
  • The reduce-only solution requires the default value
from functools import reduce

grades = [
    {
        'subject': 'math',
        'grade': 97,
    },
    {
        'subject': 'chemistry',
        'grade': 60,
    },
    {
        'subject': 'grammar',
        'grade': 75,
    }
]

print(reduce(lambda x,y: x+y, map(lambda s: s['grade'], grades))) # 232

print(reduce(lambda acc,y: acc+y['grade'], grades, 0)) #232

Output: