Dict Get Setdefault And Comprehensions
Build and query dictionaries with get, setdefault, and comprehensions so grouping logic is one expression instead of nested branches.
Code
def main() -> None:
rows = [
{'region': 'eu', 'amount': 120},
{'region': 'na', 'amount': 95},
{'region': 'eu', 'amount': 80},
{'region': 'apac', 'amount': 45},
]
# setdefault:按需建桶
buckets: dict[str, list[int]] = {}
for row in rows:
buckets.setdefault(row['region'], []).append(row['amount'])
print('buckets:', buckets)
# 字典推导:聚合到新字典
totals = {region: sum(amounts) for region, amounts in buckets.items()}
print('totals:', totals)
# get:缺席给默认
print('unknown region total:', totals.get('unknown', 0))
# 双重推导:展平回 (region, amount) 对
flat = [(region, a) for region, amounts in buckets.items() for a in amounts]
print('flat size:', len(flat))
if __name__ == '__main__':
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
buckets: {'eu': [120, 80], 'na': [95], 'apac': [45]}
totals: {'eu': 200, 'na': 95, 'apac': 45}
unknown region total: 0
flat size: 4What the code does
Dict Get Setdefault And Comprehensions is built around the function main.
Iteration happens inside for row in rows — everything outside it runs once.
Applying it
Entry signature: def main() -> None
The demo output is labeled (buckets:, totals:, unknown region total:), so every printed line maps back to its originating operation.
Interactive Tools for This Topic
FAQ
- What does Dict Get Setdefault And Comprehensions print when run?
- The script runs standalone; its 4 labeled outputs include `buckets:`, `totals:`, `unknown region total:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.