yea
yea

Reputation: 23

Using 2 differently sized lists to make key, values in a dict

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

Upvotes: 1

Views: 65

Answers (4)

Emil105
Emil105

Reputation: 158

The modulo (%) function is great for repeating lists

names = ["one", "two", "three"]
answers = ["yes", "no"]

combos = {}


def do_something():
    for i, name in enumerate(names):
        combos[name] = answers[i % len(answers)]
    print(combos)


do_something()

Upvotes: 0

Simon Hawe
Simon Hawe

Reputation: 4539

try using a dictionary comprehension

result = {name: answers[i % len(answers)] for i,name in enumerate(names)}

Upvotes: 0

mozway
mozway

Reputation: 260630

You can use itertools.cycle:

names = ["one", "two", "three"]
answers = ["yes", "no"]


from itertools import cycle
d = dict(zip(names, cycle(answers)))

Output:

{'one': 'yes', 'two': 'no', 'three': 'yes'}

Upvotes: 1

Mark
Mark

Reputation: 92440

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.

Upvotes: 6

Related Questions