Home > front end >  Generate a python dictionary with nth number of keys and incrementing values
Generate a python dictionary with nth number of keys and incrementing values

Time:04-17

I am new to python and 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:

my_list = {1:[0,1,2,3],2:[0,1,2,3,4],3:[0,1,2,3,4,5]}

Hopefully there is a python wizard out there to help.

CodePudding user response:

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)}

CodePudding user response:

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]}
  • Related