0

I'm trying to make a nested dictionary that will store a series of dictionary items, including cross references to each other, and I'm coming across (I think) very unusual behaviour.

When I try to append a single value to a list in a nested dictionary, it's also doing it to the other nested list which belongs to a different dictionary. You can see where this happen between A and B, and C and D.

data_dict = {}
count = 1

def create_new_something(category, value, parents=[], children=[]):
    global count
    data_ID = count 
    data_dict[data_ID] = {'category':category, 'value':value, 'parents':parents, 'children':children}
    count += 1
    return data_ID

def create_new_relationship(parent_ID, child_ID):

    print("Parent ID: ", parent_ID)
    print("organizer_fav.data_dict[parent_ID]:", data_dict[parent_ID])
    print ("Child ID: ", child_ID)
    print("organizer_fav.data_dict[child_ID]:", data_dict[child_ID])
    print ("Point A")
    data_dict[child_ID]['parents'].append(parent_ID)
    print ("Point B")
    print("Parent ID: ", parent_ID)
    print("organizer_fav.data_dict[parent_ID]:", data_dict[parent_ID])
    print ("Child ID: ", child_ID)
    print("organizer_fav.data_dict[child_ID]:", data_dict[child_ID])

    print ("Point C")
    data_dict[parent_ID]['children'].append(child_ID)
    print ("Point D")
    print("Parent ID: ", parent_ID)
    print("organizer_fav.data_dict[parent_ID]:", data_dict[parent_ID])
    print ("Child ID: ", child_ID)
    print("organizer_fav.data_dict[child_ID]:", data_dict[child_ID])


entity_ID = create_new_something(category='entity', value="This is the parent")
name_ID = create_new_something(category='name', value="This is the child")                
name_relationship_ID = (create_new_relationship(entity_ID, name_ID))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Phil
  • 9
  • 2
  • One of those assumptions is wrong. Which is it? One possible issue: `param = []` only creates *one* list (the default expression is only evaluated once), regardless of the number of times the function is called. – user2864740 Jan 29 '18 at 23:14
  • `create_new_something` is using default-parameters, e.g. `parents=[]` and `children=[]`. Default parameters in Python are *evaluated once* at definition time. Thus, the *same list* to the subdicts. Read more about it [here](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values) – juanpa.arrivillaga Jan 29 '18 at 23:14

0 Answers0