0

This is the worst blocker that I have ever had attempting to learn Python. I spent about 10 hours on this one and could really use help.

I want to have dictionaries hold lists in python and then access and change a specific value in those lists. When I do this the way that seems logical to me and access a key then list value, it actually replaces other key's list values.

If I just assign 100 to the key XList it prints 100 for both XList and YList. Why does assigning to one key effect the other???

And if I uncomment the assignment to YList it prints 254 for both. Why can't I assign itemized values to keys and lists like this? How can I assign specific values to lists within dictionaries and access the main lists via keys?? Why does what seems like changing just one keys list value change both key's lists???

testDictKeys= ['XList', 'YList', 'ZList']

testDict = dict.fromkeys(['XList', 'YList', 'ZList'])

noneFillerList = [None] * 30



 #Now fill all the columns and row of the dictionary with zeros

for x in range(0,2):            
    testDict[testDictKeys[x]] = noneFillerList 



for x in range(0, 29):  
 
    testDict['XList'][x]=100

    #testDict['YList'][x]=254
    
print (testDict['XList'][0])
print (testDict['YList'][0])

Any help is appreciated.

1 Answers1

0

The problem is that you only create one list and assign every dictionary to contain it. To fix the problem, be sure to create a new list to add to each dictionary.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • I see. My real code has 49 lists within the dictionary. So I was thinking that I would fill all of the keys with the same blanks list until actually assigning values. But instead. I need 49 different "blanks" lists it sounds like. All of the 49 lists have the same number of elements. – user2224727 Apr 06 '21 at 21:02
  • Thanks. That was the fundamental misunderstanding of what dictionaries are or how they work. You were 100% right. Now I need to find a way to iterate this kind of assignment with loops. It would be nice to define keys and corresponding lists from one name set. – user2224727 Apr 06 '21 at 21:17
  • @user2224727 This is has nothing to do with dictionaries. Lists are objects and when you assign `x = []`, you have a **reference** to the list object, not a copy of it. – Code-Apprentice Apr 07 '21 at 17:02
  • @user2224727 The way you are using loops and a list of keys is just fine. The problem is how you assign the same list to each key. You need to create a new list each time the loop iterates rather than just creating one list before the loop starts. – Code-Apprentice Apr 07 '21 at 17:04