ahmadre147
ahmadre147

Reputation: 15

adding to a list of values in dictionary while iteration

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

Answers (2)

balderman
balderman

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

vvvvv
vvvvv

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

Related Questions