Reputation: 2442
a challenge for a Python beginner such as I, I need to create objects which contain dictionary of lists of floating number values. I tried this flow, the objects seem to be created online, but the code stops on the line in which I try to append more values to an object that was already created, telling me that :
AttributeError: 'float' object has no attribute 'append'
This is the piece of code I'm using for this mission:
class Wimp(object):
def __init__(self, mass, definitions):
self.mass = mass
self.dN_dx = {}
for definition in definitions:
self.dN_dx[definition] = []
print definition, "added"
print "Wimp of mass", self.mass, "created."
wimp_data = {}
i=0
for mass in nu_e_mass:
if mass == nu_e_mass[i+1]:
#Saving the columns into arrays
if mass not in wimp_data:
wimp_data[mass] = Wimp(mass, definitions)
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]] = float(nu_e[j][i])
else:
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]].append(nu_e[j][i])
#print mass, "Same mass", nu_e_mass[i+1]
if i < (len(nu_e_mass)-2):
i = i+1
else:
#Integrating the columns and storing into Wimp class
#print mass, "Skipping to next mass", i, nu_e_mass[i+1]
i = i+1
If someone can spot the error it would be great as I am gazing on this code for hours now..
Upvotes: 0
Views: 3689
Reputation: 196
wimp_data[mass].dN_dx[definitions[j]] is a float, you created it. What you probably intended was:
wimp_data[mass].dN_dx[definitions[j]] = []
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]].append(float(nu_e[j][i]))
to assign a list to the mapping.
BTW: A more compact version of the whole if/else construct might be:
if mass not in wimp_data:
wimp_data[mass].dN_dx[definitions[j]] = []
wimp_data[mass] = Wimp(mass, definitions)
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]].append(nu_e[j][i])
Upvotes: 3
Reputation: 599550
Seems like you are defining the element as a float, not a list, in the first for loop:
wimp_data[mass].dN_dx[definitions[j]] = float(nu_e[j][i])
So naturally you can't append to it in the second one. Maybe you meant to make it a list containing a single float:
wimp_data[mass].dN_dx[definitions[j]] = [float(nu_e[j][i])]
Upvotes: 3