Search code examples
pythonlistdictionaryzip

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

Solution

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