Convert two lists into a dictionary

前端 未结 18 2515
囚心锁ツ
囚心锁ツ 2020-11-21 04:35

Imagine that you have:

keys = [\'name\', \'age\', \'food\']
values = [\'Monty\', 42, \'spam\']

What is the simplest way to produce the foll

18条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 04:59

    Like this:

    >>> keys = ['a', 'b', 'c']
    >>> values = [1, 2, 3]
    >>> dictionary = dict(zip(keys, values))
    >>> print(dictionary)
    {'a': 1, 'b': 2, 'c': 3}
    

    Voila :-) The pairwise dict constructor and zip function are awesomely useful: https://docs.python.org/3/library/functions.html#func-dict

提交回复
热议问题