Convert two lists into a dictionary

前端 未结 18 2603
囚心锁ツ
囚心锁ツ 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条回答
  •  我寻月下人不归
    2020-11-21 04:53

    If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:

    >>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) 
    

    Take a look Code Like a Pythonista: Idiomatic Python.

提交回复
热议问题