user3037568
user3037568

Reputation: 79

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.

Upvotes: 3

Views: 88

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160437

Alternatively, you could create the new dictionaries, iterate through the keys of the original dict and create the dictionaries accordingly:

dic = {1:(2,6), 3:(4,5)}
d1, d2 = {}, {}
for key, v in dic.items():
    d1[key], d2[key] = v 
print(d1, d2)

Which prints out:

{1: 2, 3: 4} {1: 6, 3: 5}

d1[key], d2[key] = v simply unpacks the value for v in d1[key] and d2[key] accordingly.

Upvotes: 3

Francisco
Francisco

Reputation: 11476

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)

Upvotes: 4

Related Questions