python - Loop through data looking for values from another list and add that to a dictionary -
the output of geochemical model i'm using generates 3000+ steps 300ish chemical species per step.
i have list of values species i'm interested in.
how can loop through data (main), using list of species i'm interested (species) in , add second value of relevant species list key in dictionary without having type out 100 if statements if x=='y':list['x'].append(value)
each species?
this simplified version of code:
main =[['a',1,2,3],['b',4,5,6],['c',7,8,9],['a',10,11,12],['b',13,14,15],['c',16,17,18] species = ['a', 'b', 'c'] maindict={'a':[],'b':[],'c':[]} value in main2: x in value: if x=='a':maindict['a'].append(value[2]) elif x=='b':maindict['b'].append(value[2]) elif x=='c':maindict['c'].append(value[2])
what i'm looking bit simpler like:
for value in main: if value==i in species: maindict[i].append(value[2])
but doesn't work.
output:
maindict={'a':[3,12],'b':[6,15],'c':[9,18]
you can loop through each entry in main , check if first entry in maindict, append correct entry maindict
main =[['a',1,2,3],['b',4,5,6],['c',7,8,9],['a',10,11,12],['b',13,14,15],['c',16,17,18]] species = ['a', 'b', 'c'] maindict={'a':[],'b':[],'c':[]} entry in main: if entry[0] in maindict: maindict[entry[0]].append(entry[3]) else: maindict[entry[0]] = [entry[3]] print maindict >>> {'a': [3, 12], 'c': [9, 18], 'b': [6, 15]}
Comments
Post a Comment