Python Practice › Function Programs › Program 24
Square every dictionary value
Write a Python function that returns a new dictionary with every value squared.
Input
{"a": 4, "b": 3, "c": 12, "d": 6}Output
{'a': 16, 'b': 9, 'c': 144, 'd': 36}Approach
- Dict comprehension.
Solution
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}Learn the concept
New to this topic? Read the lesson, then come back.