`trace_colors = collections.defaultdict(lambda: next(colors))` would be quite elegant.

Then you would just need `query['trace_color'] = trace_colors[query['stacktrace']]`.