Square every dictionary value

EasyFunction Programs · 24 of 39

Write a Python function that returns a new dictionary with every value squared.

Advertisement
Input
{"a": 4, "b": 3, "c": 12, "d": 6}
Output
{'a': 16, 'b': 9, 'c': 144, 'd': 36}

Approach

  1. Dict comprehension.

Solution

Python
def square_values(d):    return {k: v * v for k, v in d.items()} print(square_values({"a": 4, "b": 3, "c": 12, "d": 6}))
Output
{'a': 16, 'b': 9, 'c': 144, 'd': 36}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs