Convert two lists into a dictionary

前端 未结 18 3008
囚心锁ツ
囚心锁ツ 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 05:16

    Try this:

    >>> import itertools
    >>> keys = ('name', 'age', 'food')
    >>> values = ('Monty', 42, 'spam')
    >>> adict = dict(itertools.izip(keys,values))
    >>> adict
    {'food': 'spam', 'age': 42, 'name': 'Monty'}
    

    In Python 2, it's also more economical in memory consumption compared to zip.

提交回复
热议问题