Convert two lists into a dictionary

前端 未结 18 2494
囚心锁ツ
囚心锁ツ 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
    慢半拍i (楼主)
    2020-11-21 05:00

    Although there are multiple ways of doing this but i think most fundamental way of approaching it; creating a loop and dictionary and store values into that dictionary. In the recursive approach the idea is still same it but instead of using a loop, the function called itself until it reaches to the end. Of course there are other approaches like using dict(zip(key, value)) and etc. These aren't the most effective solutions.

    y = [1,2,3,4]
    x = ["a","b","c","d"]
    
    # This below is a brute force method
    obj = {}
    for i in range(len(y)):
        obj[y[i]] = x[i]
    print(obj)
    
    # Recursive approach 
    obj = {}
    def map_two_lists(a,b,j=0):
        if j < len(a):
            obj[b[j]] = a[j]
            j +=1
            map_two_lists(a, b, j)
            return obj
          
    
    
    res = map_two_lists(x,y)
    print(res)
    
    

    Both the results should print

    {1: 'a', 2: 'b', 3: 'c', 4: 'd'}  
    

提交回复
热议问题