Reputation: 21
I need to generate a dictionary as a pattern in the following way as an example:
x = 3 #number of keys
y = 4 #the number of values in first key, incremented in each following key
The desired output is:
{1:[0,1,2,3],2:[0,1,2,3,4],3:[0,1,2,3,4,5]}
How can I generate this output?
Upvotes: 1
Views: 72
Reputation: 19251
You can use a dictionary comprehension:
{i: list(range(j)) for i, j in zip(range(1, x + 1), range(y, y + x))}
This outputs:
{1: [0, 1, 2, 3], 2: [0, 1, 2, 3, 4], 3: [0, 1, 2, 3, 4, 5]}
Upvotes: 3
Reputation: 966
Is this ok to you?
x = 3
y = 4
my_list = {}
for i in range(1, x + 1):
my_list[i] = list(range(y))
y += 1
Or one line python using dict comprehension(maybe harder to understand):
x = 3
y = 4
my_list = {i + 1: list(range(y + i)) for i in range(x)}
Upvotes: 4