Split subdictionaries in python

Asked

Viewed 115 times

-1

Good guys, I created a ICT, and I divided it using the function:

listOfDicts = [{k:v for k,v in dictionary.items() if k%10==i} for i in range(10)]

From that, I got 10 sublists:

listOfDicts[0 a 9]
listOfDict[0]: {0: 0, 10: 5, 20: 10, 30: 15, 40: 20, 50: 25, 60: 30, 70: 35, 80: 40, 90: 45}

But what if I want to divide the sublists into equal sizes (in case size =3) and add in single Dict:

listOfDict[0]: {{0: 0, 10: 5, 20: 10}, {30: 15, 40: 20, 50: 25}, {60: 30, 70: 35, 80: 40}, {90: 45}}

1 answer

2

You can convert your dictionary to a tuple list to enable block segmentation using the slicing on that list, check it out:

def subdicts(dic, tam):
    tups = list(dic.items())
    return [dict(tups[i: i + tam]) for i in range(0, len(tups), tam)]

dic = { 0: 0, 10: 5, 20: 10, 30: 15, 40: 20, 50: 25, 60: 30, 70: 35, 80: 40, 90: 45 }
sub = subdicts(dic, 3)
print(sub)

Exit:

[{0: 0, 10: 5, 20: 10}, {30: 15, 40: 20, 50: 25}, {60: 30, 70: 35, 80: 40}, {90: 45}]

See working on Repl.it

  • Lacobus, thank you very much! That was almost the goal, but it lacked a detail. In fact I need to do this process in 10 sub-dictionaries, and store the results in a data structure, it would be possible?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.