Warm tip: This article is reproduced from serverfault.com, please click

How do I make a dictionary with a repeating value pattern?

发布于 2020-11-28 13:53:27

I am trying to create dictionary with a reapeating pattern like

{0:"A",
1:"B",
2:"C",
3:"D",
4:"A",
5:"B",
6:"C",
7:"D",}

and so on. How would I do that? I have tried using for loops, but couldn't figure it out.

I'm not even sure this is the right approach to my problem. I am solving a simulation numerous times with the same output, only changing 1 input for every loop of the simulation. Basically I end up with a DataFrame that collects the output (4 different series) for every simulation with columns

[0, 1, 2, 3, 4, 5, 6, 7, 8, ...]

which I would like to rename

["A", "B", "C", "D", "A", "B", "C", "D",...]

Alternatively, is there some sort of datatype in Python, which can provide 2 levels of categorizing like

[Simulation 1: ["A", "B", "C", "D"],
Simulation 2: ["A", "B", "C", "D"],
Simulation 3: ["A", "B", "C", "D"],
Simulation 4: ["A", "B", "C", "D"],
Simulation 5: ["A", "B", "C", "D"],
and so on...]

where "A", "B", "C" and "D" each contains a column of data output, that is different for every simulation?

Questioner
Mads
Viewed
0
juanpa.arrivillaga 2020-11-28 21:59:03

You can achieve this neatly with itertools.cycle:

In [1]: import itertools

In [2]: cols = [0, 1, 2, 3, 4, 5, 6, 7]

In [3]: dict(zip(cols, itertools.cycle('ABCD')))
Out[3]: {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'A', 5: 'B', 6: 'C', 7: 'D'}