Home > Enterprise >  Generate a dictionary with nth number of keys and letters in sequential order
Generate a dictionary with nth number of keys and letters in sequential order

Time:04-18

I need to generate a dictionary in the following format:

x = 3 #number of keys
y = 2 #number of key values (letters in sequential order)

The desired output is:

{1:[a, b],2:[c, d],3:[e,f]}

As a note, I am able to generate a list in range of letters in the following way:

list(map(chr, range(97, 98   3)))
['a', 'b', 'c', 'd']

However, I am struggling to figure out the rest.

CodePudding user response:

One way is to use an iterator:

x, y = 3, 2

letters = 'abcdefghijklmnopqrstuvwxyz' # or whatever method you prefer, like what you proposed

letters_iter = iter(letters)
output = {k 1: [next(letters_iter) for _ in range(y)] for k in range(x)}
print(output) # {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}

This assumes that x times y does not exceed 26. If you want to make the letters to cycle, then you can use itertools.cycle instead of iter:

from itertools import islice, cycle

letters_iter = cycle('abcdefghijklmnopqrstuvwxyz')
output = {k 1: [*islice(letters_iter, y)] for k in range(x)}
print(output) # {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}

CodePudding user response:

Maybe you could utilize string.ascii_lowercase:

>>> from string import ascii_lowercase
>>> x = 3
>>> y = 2
>>> {i   1: list(ascii_lowercase[i * y % 26:i * y % 26   y]) for i in range(x)}
{1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}
>>> x = 28
>>> {i   1: list(ascii_lowercase[i * y % 26:i * y % 26   y]) for i in range(x)}
{1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f'], 4: ['g', 'h'], 5: ['i', 'j'], 6: ['k', 'l'], 7: ['m', 'n'], 8: ['o', 'p'], 9: ['q', 'r'], 10: ['s', 't'], 11: ['u', 'v'], 12: ['w', 'x'], 13: ['y', 'z'], 14: ['a', 'b'], 15: ['c', 'd'], 16: ['e', 'f'], 17: ['g', 'h'], 18: ['i', 'j'], 19: ['k', 'l'], 20: ['m', 'n'], 21: ['o', 'p'], 22: ['q', 'r'], 23: ['s', 't'], 24: ['u', 'v'], 25: ['w', 'x'], 26: ['y', 'z'], 27: ['a', 'b'], 28: ['c', 'd']}
  • Related