Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using 2 different size lists to make key, values in a dict python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading