Skip to content
Advertisement

Keeping the values separately in the dictionary with for loop in Python

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.

dictionary = defaultdict(int)

for uid in range(10):
    for i in range(5):
        distance = 2*i
        dictionary[uid] = distance

Output enter image description here

My aim is to keep the key value in each loop and add on it.

Expected Output:

{0: {0,2,4,6,8,}, 1:{0,2,4,6,8,}, 2:{0,2,4,6,8} , ...

My Solution

from collections import defaultdict

dictionary = defaultdict(int)
    
    for uid in range(10):
        for i in range(5):
            distance = 2*i
            dictionary[uid].append(distance)

My solution approach is also not working there is a problem

Advertisement

Answer

Try this:

from collections import defaultdict

dictionary = defaultdict(set)
for uid in range(10):
    for i in range(5):
        distance = 2*i
        dictionary[uid].add(distance)

Output (dictionary):

> defaultdict(set,
            {0: {0, 2, 4, 6, 8},
             1: {0, 2, 4, 6, 8},
             2: {0, 2, 4, 6, 8},
             3: {0, 2, 4, 6, 8},
             4: {0, 2, 4, 6, 8},
             5: {0, 2, 4, 6, 8},
             6: {0, 2, 4, 6, 8},
             7: {0, 2, 4, 6, 8},
             8: {0, 2, 4, 6, 8},
             9: {0, 2, 4, 6, 8}})

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement