Create a dictionary object from two lists. The first list is the keys and the second list is the values of the created dictionary.

Wribreeminsl

Wribreeminsl

Answered question

2021-10-09

Create a dictionary object from two lists. The first list is the keys and the second list is the values of the created dictionary. Note that keys are unique. Only the first occurrence of a key and the corresponding value should be appended to the created dictionary. Example: A = [1, 2, 2, 5, 1, 20, 5, 1, 0, -10], B = [A, B, C, D, E, F, G, H, I, J], created dictionary: {1: A, 2: B, 5: D, 20: F, 0: I, -10: J}

Answer & Explanation

Nathaniel Kramer

Nathaniel Kramer

Skilled2021-10-10Added 78 answers

What we need to do is iterate over both lists, check if the key is already in the dictionary, and then add the key-value pair if it is not. We can do that first part using the zip() function which roughly takes two lists and generates a list of tuples like so.
>>> lst1 = [1, 3, 6]
>>> lst2 = [one, three, six]
>>> list(zip(lst1, lst2))
[(1, one), (3, three), (6, six)]
Note: the "roughly" part is why the list() function is necessary here.
Checking if a key is in a dictionary is as simple as key in dictionary and adding a new key-value pair uses regular bracket notation.
So heres

Do you have a similar question?

Recalculate according to your conditions!

Ask your question.
Get an expert answer.

Let our experts help you. Answer in as fast as 15 minutes.

Didn't find what you were looking for?