30秒学会 Python 片段 · 2023年2月14日

30秒学会 Python 片段 – Lists to dictionary

Combines two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values.
The values of the first list need to be unique and hashable.

  • Use zip() in combination with dict() to combine the values of the two lists into a dictionary.

代码实现

def to_dictionary(keys, values):
  return dict(zip(keys, values))

使用样例

to_dictionary(['a', 'b'], [1, 2]) # { a: 1, b: 2 }

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