30秒学会 Python 片段 · 2023年12月24日

30秒学会 Python 片段 – 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.

  • Use dict.items() to iterate over the dictionary, assigning the values produced by fn to each key of a new dictionary.

代码实现

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}

翻译自:https://www.30secondsofcode.org/python/s/map-values