Search code examples
pythonlistdictionaryenumerate

Can someone help me understand the code below


I want to understand how the code below works can someone help me through this See the code below

keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] 
dict = {} 
for index, item in enumerate(keys):
        dict[item] = values[index]

Solution

  • keys = ['name', 'age', 'food'] 
    values = ['Monty', 42, 'spam'] 
    
    d = {}
    
    for key, value in zip(keys,values):
        d[key] = value
    
    print (d)
    

    Output:

    {'name': 'Monty', 'age': 42, 'food': 'spam'}
    

    You code example was, indeed, quite complicated. This zip() method makes a list of lists (nested list).

    To comment your code:

    keys = ['name', 'age', 'food'] 
    values = ['Monty', 42, 'spam'] 
    dic = {} 
    #index is common to keys and values lists, item is the element at index for keys list
    for index, item in enumerate(keys):
            #You set the key item with the element found at the corresponding index in values
            dic[item] = values[index]