Convert two lists into a dictionary

前端 未结 18 2486
囚心锁ツ
囚心锁ツ 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.

    0 讨论(0)
  • 2020-11-21 04:53

    method without zip function

    l1 = [1,2,3,4,5]
    l2 = ['a','b','c','d','e']
    d1 = {}
    for l1_ in l1:
        for l2_ in l2:
            d1[l1_] = l2_
            l2.remove(l2_)
            break  
    
    print (d1)
    
    
    {1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}
    
    0 讨论(0)
  • 2020-11-21 04:57
    >>> keys = ('name', 'age', 'food')
    >>> values = ('Monty', 42, 'spam')
    >>> dict(zip(keys, values))
    {'food': 'spam', 'age': 42, 'name': 'Monty'}
    
    0 讨论(0)
  • 2020-11-21 04:57

    For those who need simple code and aren’t familiar with zip:

    List1 = ['This', 'is', 'a', 'list']
    List2 = ['Put', 'this', 'into', 'dictionary']
    

    This can be done by one line of code:

    d = {List1[n]: List2[n] for n in range(len(List1))}
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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'}
    
    0 讨论(0)
提交回复
热议问题