ZipMap
Zip two lists into a dictionary
Last updated
Zip two lists into a dictionary
Last updated
Within Doc2Doc we need to map certain properties from one document to properties of another document. Complete the recursive zipmap
function.
It takes two lists as input and returns a where the first list provides the keys and the second list provides the values.
Example usage:
Here's the :
If either the keys
or values
list is empty, return an empty dictionary (base case)
Recursively call zipmap
on all but the first elements from keys
and values
Add the first element of keys
to the resulting dictionary, and set its value to the first element in values
Return the updated dictionary
It zips two lists together into a dictionary!
It takes a list of keys
and a list of values
.
It pairs them up so each key gets a value.
should return:
This function builds the dictionary backwards using recursion.
Step 1: Base Case (When to Stop)
If either list is empty, return an empty dictionary {}
.
This stops the function from calling itself forever (which would break things).
Step 2: Recursive Call (Breaking the Problem Down)
This removes the first element from both lists.
Calls zipmap() again with the smaller lists.
This keeps happening until we hit the base case.
Third Call:
Calls zipmap([], [])
Will add "c": 3 later
Fourth Call (Base Case):
Returns {}
(empty dictionary)
Each call adds back a key-value pair:
zipmap(["c"], [3]) → { "c": 3 }
zipmap(["b", "c"], [2, 3]) → { "c": 3, "b": 2 }
zipmap(["a", "b", "c"], [1, 2, 3]) → { "c": 3, "b": 2, "a": 1 }
🎉 Final Result: