RuntimeError: dictionary changed size during iteration python code example

Example: dictionary changed size during iteration

# incur this problem here: 
# https://leetcode.com/problems/binary-trees-with-factors/

arr = [2,4,5,10]
dp = collections.defaultdict(int)

# this would create error since dp[x/i] is creating a new key with x/i
# thus dictionary changed size during iteration
# to solve this problem, dp.copy() can be used but with time complexity O(n^2)
for x in sorted(arr):
    dp[x] = sum(dp[i]*dp[x/i] for i in dp if x % i == 0) + 1
return sum(dp.values()) % (10**9 + 7)

# use `get` since it just query the dictionay without creating a new key
# time complexity: O(n)
for x in sorted(arr):
	dp[x] = sum(dp[i] * dp.get(x / i, 0) for i in dp if x % i == 0) + 1
return sum(dp.values()) % (10**9 + 7)