0

I spend several hours on this and yet I'm unable to understand what is going on. In my belief this would work in other languages (e.g. Javascript), but in Python I don't know what is going on.

I am using a simple MongoDB DataStructure that consists of

field1: "value1" field2: "value2" fieldn: "valuen" fieldM: Array

and the target is to print out every value of the array along with its "parent". The Python function I have written for this purpose looks like this

def manageonts(sProj):
    ontologies = []
    my_ontology = OntologyDefinition()
    for o in OntologyDefinition.GetAll(sProj): #parent items 
        for l in o.OntologyDefinitions: #child items
            my_ontology.a_type = l[0] #we can access the fields of the array via this method
            my_ontology.a_text = l[1]
            my_ontology.a_subtopic = l[2]
            my_ontology.a_weight = l[3]
            my_ontology.a_weight_if_referenced = l[4]
            ontologies.append(my_ontology)
    for ont in ontologies:
        print(ont.a_text)

while OntologyDefinition is a class that has fields for every "column", including the fields of the array.

I would assume that the last loop would return results such as

database
date
data
datum
design
event
figure

But instead it seems like the ontologies list contains only the last value:

capacity
capacity
capacity
capacity
capacity
capacity

What am I doing wrong here? I am particularly interested why this behaviour happens. Thank you all for your help.

gue
  • 67
  • 8

1 Answers1

1

You need to move this line:

my_ontology = OntologyDefinition()

inside the for loops. Otherwise you are only creating one OntologyDefinition and referencing it many times, overwriting its values every time through the loop.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436