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 = map(chr, range(97, 97 26))
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
from string import ascii_lowercase
x, y = 3, 2
letters_iter = cycle(ascii_lowercase)
output = {k 1: [*islice(letters_iter, y)] for k in range(x)}
print(output) # {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}
(Here, I used islice
to shorten the inner list comprehension further. The star *
in [*...]
is (generalized) unpacking. Also I used string.ascii_lowercase
, but any other ways would work.)
CodePudding user response:
There are many ways to do this. So let's have a discrete function like this:
from string import ascii_lowercase as LC
def make_dict(x, y):
return {k 1:list(LC[k*y:(k 1)*y]) for k in range(x)}
print(make_dict(3, 2))
Output:
{1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}