Reputation: 15
I was trying to count divisors of 10 numbers and add them as value to their dictionary but when I was trying to append other divisors to the list of values it didn't happen and got replaced. I wonder why this happens.
a = []
t = dict()
for i in range(10):
a.append(input())
a = [int(i) for i in a]
for num in a:
for x in range (1, num + 1):
if (num % x) == 0:
t[num] = []
t[num].append(x)
print(t)
Upvotes: 0
Views: 48
Reputation: 23815
defaultdict can make your life easier here since it will take care if the list allocation.
from collections import defaultdict
a = []
t = defaultdict(list)
for i in range(10):
a.append(input())
a = [int(i) for i in a]
for num in a:
for x in range (1, num + 1):
if (num % x) == 0:
t[num].append(x)
print(t)
Upvotes: 1
Reputation: 31609
It's because you reinitialize t[num]
when you should not:
a = []
t = dict()
for i in range(10):
a.append(input())
a = [int(i) for i in a]
for num in a:
for x in range (1, num + 1):
if (num % x) == 0:
if num not in t: # Here: init t[num] to [] only if it does not yet exist
t[num] = []
t[num].append(x)
print(t)
Upvotes: 1