-1

I am facing a problem in assigning values to dictionary. I want a changing list (which is being updated by every iteration of a loop) assigned to the keys of my dictionary by using a for loop. But the problem is the lists are eventually same for all of the keys.

Let me show it with example:

months = ['jan', 'feb', 'mar', 'apr']  # this is the list of keys of the Dictionary
numbers = []
sqrDict = {}
i = 1
for m in months:
    numbers.append(i**2)
    sqrDict[m] = numbers
    i += 1

print('sqrDict =', sqrDict)

I actually want my dictionary to be as:

sqrDict = {'jan': [1], 'feb': [1, 4], 'mar': [1, 4, 9], 'apr': [1, 4, 9, 16]}

But what I am having is:

sqrDict = {'jan': [1, 4, 9, 16], 'feb': [1, 4, 9, 16], 'mar': [1, 4, 9, 16], 'apr': [1, 4, 9, 16]}

I don't understand what the problem is. What is going wrong with my code?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0

The issue are having is that you are setting sqrDict[m] = numbers. At the end, all the values in the dict point to numbers. This should fix your code, as it assigns each position in sqrDict to the value of numbers at the time, instead of pointing to it, which is achieved by changing numbers[] to numbers[:] as shown below:

months = ['jan', 'feb', 'mar', 'apr'] #this is the list of keys of the Dictionary
numbers = []
sqrDict = {}
i = 1
for m in months:
    numbers.append(i**2)
    sqrDict[m] = numbers[:]
    i += 1

print('sqrDict = ',sqrDict)
3ddavies
  • 546
  • 2
  • 19