Convert two lists into a dictionary

前端 未结 18 2488
囚心锁ツ
囚心锁ツ 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: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'}  
    
    0 讨论(0)
  • 2020-11-21 05:03
    keys = ['name', 'age', 'food']
    values = ['Monty', 42, 'spam']
    index=np.arange(0,len(keys)-1)
    
    df=pd.DataFrame(list(zip(keys,values)), columns=['keys','values'])
    df.set_index('keys')
    print(df.head())
    
    data_dict = df.iloc[index].set_index('keys')['values'].to_dict() 
    print(data_dict)
    

    zip creates a generator of parallel values list() instantiates the full generator and passing that into the dataframe which converts the whole expression. resulting output:

    two lists:

        keys values
     0  name  Monty
     1   age     42
     2  food   spam
     
    

    Output: dictionary

     {'name': 'Monty', 'age': 42}
    
    0 讨论(0)
  • 2020-11-21 05:04

    A more natural way is to use dictionary comprehension

    keys = ('name', 'age', 'food')
    values = ('Monty', 42, 'spam')    
    dict = {keys[i]: values[i] for i in range(len(keys))}
    
    0 讨论(0)
  • 2020-11-21 05:05

    Here is also an example of adding a list value in you dictionary

    list1 = ["Name", "Surname", "Age"]
    list2 = [["Cyd", "JEDD", "JESS"], ["DEY", "AUDIJE", "PONGARON"], [21, 32, 47]]
    dic = dict(zip(list1, list2))
    print(dic)
    

    always make sure the your "Key"(list1) is always in the first parameter.

    {'Name': ['Cyd', 'JEDD', 'JESS'], 'Surname': ['DEY', 'AUDIJE', 'PONGARON'], 'Age': [21, 32, 47]}
    
    0 讨论(0)
  • 2020-11-21 05:06

    you can use this below code:

    dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))
    

    But make sure that length of the lists will be same.if length is not same.then zip function turncate the longer one.

    0 讨论(0)
  • 2020-11-21 05:07

    Solution as dictionary comprehension with enumerate:

    dict = {item : values[index] for index, item in enumerate(keys)}
    

    Solution as for loop with enumerate:

    dict = {}
    for index, item in enumerate(keys):
        dict[item] = values[index]
    
    0 讨论(0)
提交回复
热议问题