Windy71
Windy71

Reputation: 909

How to make a dict from a key list which is longer than the value list

I have a dict I wish to make which will be quite big, 600 key value pairs. The keys will be integers, the values will be from a list of 3 letters (A,B and C). If I generate a list of the keys how can I 'map' the appropriate value to the key.

Code

my_list = list(range(1,11,1))
my_letters = ["A", "B", "C"]
my_dict = {}

for k in my_list:
    for v in my_letters
# I know it isn't going to be nested for loops

Desired output

#my_dict = {"1" : "A", "2" : "B", "3" : "C", "4" : "A", ... "10" : "A"}

Upvotes: 3

Views: 154

Answers (2)

Mady Daby
Mady Daby

Reputation: 1269

Here you can access the corresponding value in my_letters by using the remainder of the division of the key by the length of the list of letters.

my_list = list(range(1,11,1))
my_letters = ["A", "B", "C"]
my_dict = {}

for k in my_list:
    my_dict[k] = my_letters[k%len(my_letters)-1]

print(my_dict)

Output:

{1: 'A', 2: 'B', 3: 'C', 4: 'A', 5: 'B', 6: 'C', 7: 'A', 8: 'B', 9: 'C', 10: 'A'}       

As pointed out by @DarryIG, using dict comprehension:

my_letters = ["A", "B", "C"]
my_dict =  {k:my_letters[k%len(my_letters)-1] for k in range(1, 11)}

Upvotes: 5

Guy
Guy

Reputation: 50819

You can use itertools.cycle to loop over the shorter list and the range object together with zip, and create the dictionary with dict comprehensions

my_dict = {x: z for x, z in zip(range(1, 11), itertools.cycle(["A", "B", "C"]))}
print(my_dict) # {1: 'A', 2: 'B', 3: 'C', 4: 'A', 5: 'B', 6: 'C', 7: 'A', 8: 'B', 9: 'C', 10: 'A'}

As a side note, no need to convert range to list or to specify step in range if it's 1.

Upvotes: 2

Related Questions