There is a dictionary like {key: [list of two items]}

d1 = {1:[10, 5], 2:[40, 8], 3:[144, 12], 4:[55, 11]} 

how to convert it into a dictionary, where the value is the result of dividing the zero element of the list by the first:

 d2 = {1:(10/5), 2:(40/8), 3:(144/12), 4:(55/11)} 

to end up with:

 d2 = {1:2, 2:5, 3:12, 4:5} 

    1 answer 1

    Elementary:

     d2 = {key: value[0]//value[1] for key, value in d1.items()} 

    Result:

     {1: 2, 2: 5, 3: 12, 4: 5} 

    The .items() method of the dictionary returns an iterator, which is a sequence of tuples (ключ, значение) , which are then decompressed into the corresponding variables. If you print list(d1.items()) , the result will be as follows:

     [(1, [10, 5]), (2, [40, 8]), (3, [144, 12]), (4, [55, 11])] 

    // is an integer division, the result of the division will be rounded to the whole. If you need a float (without rounding), then for the Python 3 version you need to change the division to "single" ( / ), and for the Python 2 version, also convert at least one of the arguments to float :

     d2 = {key: float(value[0])/value[1] for key, value in d1.items()} 

    For Python 3 is easier:

     d2 = {key: value[0]/value[1] for key, value in d1.items()} 

    Result:

     {1: 2.0, 2: 5.0, 3: 12.0, 4: 5.0}