user3037568 user3037568 - 1 year ago 62
Python Question

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
, 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 Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download