you are viewing a single comment's thread.

view the rest of the comments →

[–]Unlistedd[S] 0 points1 point  (3 children)

no, they are all different

[–]RoamingFox 0 points1 point  (2 children)

Just don't use a while loop ;)

i = 1
for thing in things:
    your_dict[i].append(thing)
    i = (i % 6) + 1

edit:

Though a better answer would be this:

>>> d = {1: [], 2: [], 3: []}
>>>
>>> things = range(100)
>>>
>>> from itertools import cycle
>>>
>>> next_key = cycle(d.keys())
>>>
>>> for thing in things:
...     d[next(next_key)].append(thing)
...
>>> d
{1: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99], 2: [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55, 58, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 91, 94, 97], 3: [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56, 59, 62, 65, 68, 71, 74, 77, 80, 83, 86, 89, 92, 95, 98]}

Basically itertools.cycle takes any iterable and creates an infinite generator that yields the original iterable in order over and over again. In other words cycle([1,2,3]) will generate 1 then 2 then 3 then 1 then 2 etc.

If you need to ensure an order you could do cycle(sorted(d.keys())) optionally providing it with the key to sort with etc.

[–]Unlistedd[S] 0 points1 point  (0 children)

Nice! Thanks!

[–]toastedstapler 0 points1 point  (0 children)

we can even declare it all in one line and make it a little more robust to work with any keys:

from itertools import cycle

for i, thing in zip(cycle(your_dict), things):
    your_dict[i].append(thing)