Convert two lists into a dictionary

前端 未结 18 2605
囚心锁ツ
囚心锁ツ 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
    2020-11-21 05:08

    • 2018-04-18

    The best solution is still:

    In [92]: keys = ('name', 'age', 'food')
    ...: values = ('Monty', 42, 'spam')
    ...: 
    
    In [93]: dt = dict(zip(keys, values))
    In [94]: dt
    Out[94]: {'age': 42, 'food': 'spam', 'name': 'Monty'}
    

    Tranpose it:

        lst = [('name', 'Monty'), ('age', 42), ('food', 'spam')]
        keys, values = zip(*lst)
        In [101]: keys
        Out[101]: ('name', 'age', 'food')
        In [102]: values
        Out[102]: ('Monty', 42, 'spam')
    

提交回复
热议问题