Map Dictionary Values

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, a dictionary is a collection of key-value pairs. Sometimes, we need to transform the values of a dictionary using a function. This challenge will test your ability to create a function that takes a dictionary and a function as arguments and returns a new dictionary with the same keys as the original dictionary and values generated by running the provided function for each value.

Map Dictionary Values

Write a function map_values(obj, fn) that takes a dictionary obj and a function fn as arguments and returns a new dictionary with the same keys as the original dictionary and values generated by running the provided function for each value.

def map_values(obj, fn):
  return dict((k, fn(v)) for k, v in obj.items())
users = {
  'fred': { 'user': 'fred', 'age': 40 },
  'pebbles': { 'user': 'pebbles', 'age': 1 }
}
map_values(users, lambda u : u['age']) ## {'fred': 40, 'pebbles': 1}

Summary

In this challenge, you learned how to create a function that takes a dictionary and a function as arguments and returns a new dictionary with the same keys as the original dictionary and values generated by running the provided function for each value. This is a useful technique for transforming the values of a dictionary.

Other Python Tutorials you may like