I’ve reviewed many questions in StackOverflow that may be related to my question Q1, Q2, Q3, Q4 None of them are related to my question. Apart from these, I examined almost 20 questions here.
I created a sample code block to explain my problem simply. My aim is to add data to a dictionary in for loop.
When I run the code block below, the output is as follows.
JavaScript
x
7
1
dictionary = defaultdict(int)
2
3
for uid in range(10):
4
for i in range(5):
5
distance = 2*i
6
dictionary[uid] = distance
7
My aim is to keep the key value in each loop and add on it.
Expected Output:
JavaScript
1
2
1
{0: {0,2,4,6,8,}, 1:{0,2,4,6,8,}, 2:{0,2,4,6,8} ,
2
My Solution
JavaScript
1
9
1
from collections import defaultdict
2
3
dictionary = defaultdict(int)
4
5
for uid in range(10):
6
for i in range(5):
7
distance = 2*i
8
dictionary[uid].append(distance)
9
My solution approach is also not working there is a problem
Advertisement
Answer
Try this:
JavaScript
1
8
1
from collections import defaultdict
2
3
dictionary = defaultdict(set)
4
for uid in range(10):
5
for i in range(5):
6
distance = 2*i
7
dictionary[uid].add(distance)
8
Output (dictionary
):
JavaScript
1
13
13
1
> defaultdict(set,
2
{0: {0, 2, 4, 6, 8},
3
1: {0, 2, 4, 6, 8},
4
2: {0, 2, 4, 6, 8},
5
3: {0, 2, 4, 6, 8},
6
4: {0, 2, 4, 6, 8},
7
5: {0, 2, 4, 6, 8},
8
6: {0, 2, 4, 6, 8},
9
7: {0, 2, 4, 6, 8},
10
8: {0, 2, 4, 6, 8},
11
9: {0, 2, 4, 6, 8}})
12
13