0
original_number = int(input('Please enter a number: '))

all_divisors = {} # lists all of the divisors
b = [1]

# adds 1 to the end of b, then puts it into all_divisors with key
# equal to its divisor, its value is a list of 1's with a number of 1's
# equal to the key
for a in range(2, original_number + 1):
    b.append(1)
    all_divisors[a] = b
    print(all_divisors) # just to make sure everything works properly

What I'm trying to do is get a result like:

Please enter a number: 4
{2: [1, 1]}
{2: [1, 1], 3: [1, 1, 1]}
{2: [1, 1], 3: [1, 1, 1], 4: [1, 1, 1, 1]}

Instead, I get:

Please enter a number: 4
{2: [1, 1]}
{2: [1, 1, 1], 3: [1, 1, 1]}
{2: [1, 1, 1, 1], 3: [1, 1, 1, 1], 4: [1, 1, 1, 1]}

How do I get each value in the dictionary to be the value of b when it's passed in? (That is the correct use of 'pass in' right?)

Andrew Pampuch
  • 65
  • 1
  • 10

2 Answers2

0

All your dictionary values are references to the same list, b. Therefor they will be updated when b is updated. You need to make a copy of b for each key.

for a in range(2, original_number + 1):
b.append(1)
all_divisors[a] = b[:]
print(all_divisors)

Where b[:] is a new list, instead of a reference to the original list b

user3636636
  • 2,409
  • 2
  • 16
  • 31
0
original_number = 4
for i in range(2,original_number+1):
    print dict((j,[1]*j) for j in range(2,i+1))

maybe i guess?

but to answer the original question about the original code

all_divisors[a] = b[:]

should fix the problem

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179