user3037568 user3037568 - 28 days ago 6
Python Question

python separating dictionary into smaller dictionaries

I have a dictionary and want to divide it into smaller dictionaries,

for example for dic = {1:(2,6), 3:(4,5)}

I want to loop it and have a "current" dictionary current = {1:2, 3:4} for first iteration, and current {1:6, 3:5} for the second iteration. Here's what I've tried (and doesn't work)

dic = {1:(2,6), 3:(4,5)}

for i in range (0,1):
for key in dic:
current = {}
current[key] = dic[key][i]
print (current)


this outputs {3:4} and {3:5}, it skips the key "1" for some reason. How do i fix this?

Also, how do I find the number of the values of the keys assuming every key has equal number of values? e.g. for {2:[3,4,5,7], 3:[1,0,3,1]} that would be 4.

Answer

You are overwriting current on each iteration, define it before iterating, and range(0, 1) loops through [0] only:

dic = {1:(2,6), 3:(4,5)}

for i in range(2):
    current = {}
    for key in dic:
        current[key] = dic[key][i]
    print(current)
Comments