Skip to content

Home

Map dictionary values

Creates a dictionary with the same keys as the provided 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}

More like this

Start typing a keyphrase to see matching snippets.