Convert two lists into a dictionary

前端 未结 18 2500
囚心锁ツ
囚心锁ツ 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:59

    with Python 3.x, goes for dict comprehensions

    keys = ('name', 'age', 'food')
    values = ('Monty', 42, 'spam')
    
    dic = {k:v for k,v in zip(keys, values)}
    
    print(dic)
    

    More on dict comprehensions here, an example is there:

    >>> print {i : chr(65+i) for i in range(4)}
        {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}
    

提交回复
热议问题