I want to split this dictionary into equal chunks.
{0: 'media', 1: 'alta', 2: 'media', 3: 'media', 4: 'alta', 5: 'alta', 6: 'baja', 7: 'media', 8: 'media', 9: 'media', 10: 'media', 11: 'media'}
Output
{0: 'media', 1: 'alta', 2: 'media'}
{0: 'media', 1: 'alta', 2: 'alta'}
{0: 'baja', 1: 'media', 2: 'media'}
{0: 'media', 1: 'media', 2: 'media'}
Do you have any ideas without using external modules (numpy and etc.).
CodePudding user response:
If you're looking to create a list of dictionaries, then your best bet would probably lie in for loops. The following code outputs what you're looking for.
d = {0: 'media', 1: 'alta', 2: 'media', 3: 'media', 4: 'alta', 5: 'alta', 6: 'baja', 7: 'media', 8: 'media', 9: 'media', 10: 'media', 11: 'media'}
list_o_dict = []
# Go through the dictionary, but skip ahead by 3 each time
for i in range(0, len(d), 3):
# Append a new dictionary to the list
list_o_dict.append({0 : d[i], 1 : d[i 1], 2 : d[i 2]})
# This can be omitted, but just prints the list out
for i in list_o_dict:
print(i)
CodePudding user response:
You can create a generator. Assuming you want the new dictionary keys to start from 0 each time, here is what you can do:
dict_input = {0: 'media', 1: 'alta', 2: 'media', 3: 'media', 4: 'alta', 5: 'alta', 6: 'baja', 7: 'media', 8: 'media', 9: 'media', 10: 'media', 11: 'media'}
# value_count is the dictionary's item limit
def split_dict(dict_obj, value_count):
new_dict = {}
number = 0
for key, value in dict_obj.items():
new_dict[number] = value
number = 1
if value_count == number:
yield new_dict
new_dict = {} # the dictionary resets after the dictionary is full
number = 0 # if you want the index to start from zero in the next dictionary
running this function will return a generator which you can iterate to get the results.
split_dict(dict_input, 2)
for result in split_dict(dict_input, 2):
print(result)
This should give you that output
{0: 'media', 1: 'alta', 2: 'media'}
{0: 'media', 1: 'alta', 2: 'alta'}
{0: 'baja', 1: 'media', 2: 'media'}
{0: 'media', 1: 'media', 2: 'media'}
CodePudding user response:
with itertools.islice
from itertools import islice
def split(d: dict[int, str], chunks: int):
chunk_len = len(d) // chunks
chunks_list = []
for i in range(chunk_len):
c = chunk_len * i
chunks_list.append(dict())
for k, v in islice(a.items(), c, c chunk_len):
chunks_list[i].update({k: v})
return chunks_list
ss = split(a, 4)
-> [{0: 'media', 1: 'alta', 2: 'media'},
{3: 'media', 4: 'alta', 5: 'alta'},
{6: 'baja', 7: 'media', 8: 'media'}]