Search code examples
pythondictionaryiteratorlist-comprehensiondictionary-comprehension

Making a dictionary with keys being lists of increasing values


I'm trying to figure out how to make a dictionary that looks like this:

1: [0, 1, ..., 26]
2: [27, 29, ..., 53]
3: [55, 56, ..., 80]

I can't think of a quick way to do this. Can anybody think of an elegant way to code a dictionary that looks like this?

Thanks!


Solution

  • Both of these answers assume that the lists generated for each dictionary key are of equal lengths.

    First list containing zero:

    dict_gen = lambda n, x: {i + 1:range(i * (x + 1), (i + 1) * (x + 1)) for i in range(n)}
    
    >>>dict_gen(3, 27)
    

    Output:

    {
    1: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27],
    2: [28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55],
    3: [56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83]
    }
    

    First list not containing zero:

    dict_gen = lambda n, x: {i + 1:range(i * x + 1, (i + 1) * x + 1) for i in range(n)}
    
    >>>dict_gen(3, 27)
    

    Output:

    {
    1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27],
    2: [28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54],
    3: [55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81]
    }