The challenge that I’m facing is trying to figure out how to use 2 lists for a dict with one list having less items than the other. For each item in the list names, I’d like to add the item as a key in the combos dict while also adding one item from the answers list as a value to the key.. but once the smaller list reaches it’s end adding values I’d like to restart from the beginning until every key has a value.
It’s hard for me to google an answer because I can’t really figure out how to accurately describe my question.
names = ["one", "two", "three"]
answers = ["yes", "no"]
combos = {}
def do_something():
#do stuff
print(combos)
do_something()
desired output:
{"one": "yes", "two": "no", "three": "yes"}
>Solution :
itertools.cycle() is meant for exactly this kind of challenge:
from itertools import cycle
names = ["one", "two", "three"]
answers = ["yes", "no"]
combos = dict(zip(names, cycle(answers)))
print(combos)
# {'one': 'yes', 'two': 'no', 'three': 'yes'}
Given an iterable like a list, it will just keep producing values in order. Since zip() stops when the last iterable runs out, it stops producing values when names has nothing left.