snippetpythonTip
Map dictionary values
Viewed 0 times
mappythondictionaryvalues
Problem
Have you ever wanted to create a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value? Luckily, there's a quick and easy way to do this in Python.
Using
Using
dict.items(), you can iterate over the dictionary. Then, you can assign the values produced by the function to each key of a new dictionary. And that's it!Solution
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}Code Snippets
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}Context
From 30-seconds-of-code: map-values
Revisions (0)
No revisions yet.