30秒学会 Python 片段 · 2022年7月31日

30秒学会 Python 片段 – Invert dictionary

Inverts a dictionary with unique hashable values.

  • Use dictionary.items() in combination with a list comprehension to create a new dictionary with the values and keys inverted.

代码实现

def invert_dictionary(obj):
  return { value: key for key, value in obj.items() }

使用样例

ages = {
  'Peter': 10,
  'Isabel': 11,
  'Anna': 9,
}
invert_dictionary(ages) # { 10: 'Peter', 11: 'Isabel', 9: 'Anna' }

翻译自:https://www.30secondsofcode.org/python/s/invert-dictionary