Home > Net >  Splitting dictionary values (list) into constant chunks
Splitting dictionary values (list) into constant chunks

Time:06-17

I have a dictionary of topics with lists as values.

topics = {'sports':sports, 'food':food, 'movies':movies, 'singers':singers, 'goats':goats}

These are the values

sports = ['soccer','basketball','tennis'],
food = ['burger','fried rice', 'spaghetti','curry', 'lamb','wings']
movies = ['spider man', 'batman', 'iron man', 'hustle', 'desperado']
singers = ['drake']
goats = ['messi', 'jordan']

I want to transform the dictionary in a manner that, given size k, the elements in the list shouldn't be greater than k. If they are, create a new list, and put the elements in. For instance, if k = 2, that means I want the list values to be split like this:

{'goats':['messi', 'jordan'],
 'sports_1', ['soccer','basketball'],
 'sports_2': ['tennis'], 
 'food_1': ['burger','fried rice'],
 'food_2': ['spaghetti','curry'],
 'food_3': ['lamb','wings'],
 'movies_1': ['spider man', 'batman'],
 'movies_2: ['iron man', 'hustle'],
 'movies_3':['desperado'],
 'singers':['drake']}

CodePudding user response:

Try:

def chunks(lst, n):
    for i in range(0, len(lst), n):
        yield lst[i : i   n]


out = {}
for k, v in topics.items():
    c = list(chunks(v, 2))
    if len(c) == 1:
        out[k] = c[0]
    else:
        for i, ch in enumerate(c, 1):
            out[f"{k}_{i}"] = ch

print(out)

Prints:

{
    "sports_1": ["soccer", "basketball"],
    "sports_2": ["tennis"],
    "food_1": ["burger", "fried rice"],
    "food_2": ["spaghetti", "curry"],
    "food_3": ["lamb", "wings"],
    "movies_1": ["spider man", "batman"],
    "movies_2": ["iron man", "hustle"],
    "movies_3": ["desperado"],
    "singers": ["drake"],
    "goats": ["messi", "jordan"],
}
  • Related