d = {1: [1, 2, 3, 4], 3: [5, 7, 9], 9: [9, 0, 5, 4, 6]}
Вариант #1.1 (21.7 µs per loop) - кстати, v.pop() было бы быстрее, чем v.pop(0):
while d:
for k, v in d.copy().items():
print(f'{k}:{v.pop(0)}') if v else d.pop(k)
Вариант #1.2 (32.2 µs per loop):
while d:
for key, vals in tuple(d.items()):
try:
print(f'{key}:{vals.pop(0)}')
except IndexError:
del d[key]
Вариант #2 (15.7 µs per loop) - самый быстрый, т.к. нет try/except и модификации:
from itertools import chain, cycle, zip_longest
def solve(mapping, placeholder=None):
keys = cycle(mapping.keys())
vals = chain(*zip_longest(*mapping.values(), fillvalue=placeholder))
for key, val in zip(keys, vals):
if val is not placeholder:
print(f'{key}:{val}')
solve({1: [1, 2, 3, 4], 3: [5, 7, 9], 9: [9, 0, 5, 4, 6]})
Вариант #3 (27.2 µs per loop):
from itertools import repeat, starmap
def solve(mapping):
iterf = lambda key, vals: (repeat(key), iter(vals))
items = tuple(starmap(iterf, mapping.items()))
for _ in max(mapping.values(), key=len):
for ikeys, ivals in items:
try:
print(f'{next(ikeys)}:{next(ivals)}')
except StopIteration:
pass
solve({1: [1, 2, 3, 4], 3: [5, 7, 9], 9: [9, 0, 5, 4, 6]})