Trollsors
Trollsors

Reputation: 492

Assign list values to dictionary keys

So I want to loop over a dictionary and a list simultaneously without them being nested. What I really mean is:

for i,c in enumerate(dictionary) and for k in range(len(list)):
       dictionary[c] = list[k]

So it basically loops over one dictionary and I can assign values to the dictionary with a list.

Upvotes: 1

Views: 9783

Answers (2)

cs95
cs95

Reputation: 403198

IIUC, you are trying to reassign existing keys to list values. This is something you can only do from python-3.7 onwards (or 3.6 if you use CPython). This can be done either through direct reassignment,

dictionary = dict(zip(dictionary, lst))

Or, if they are not the same length, and there are keys you want to preserve, use dict.update:

dictionary.update(dict(zip(dictionary, lst)))

Additionally, it is unwise to name variables after builtin objects (such as list).

Upvotes: 10

Yoav Glazner
Yoav Glazner

Reputation: 8041

zip is your friend

dictionary.update(zip(dictionary, lst))

Upvotes: 4

Related Questions