python - Adding numbers in a list and converting it to a dictionary -


i'm sure must simple, i'm python noob, need help. have list looks following way:

foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']] 

notice every word has 1 or 2 numbers it. want substract number 2 number 1 , come dictionary is: word, number. foo this:

foo = {'able','0.125'},{'unable', '-0.75'}... 

it tried doing:

bar=[] a,b,c in foo:    d=float(a)-float(b)    bar.append((c,d)) 

but got error:

valueerror: not convert string float:  

'' cannot converted string.

bar = [] a,b,c in foo:     d = float(a or 0) - float(b or 0)     bar.append((c,d)) 

however, not make dictionary. want:

bar = {} a,b,c in foo:     d = float(a or 0)-float(b or 0)     bar[c] = d 

or shorter way using dictionary comprehensions:

bar = {sublist[2]: float(sublist[0] or 0) - float(sublist[1] or 0) sublist in foo} 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -