ZipMap
Zip two lists into a dictionary
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 dictionary where the first list provides the keys and the second list provides the values.
Example usage:
zipped = zipmap(
["Avatar: The Last Airbender", "Avatar (in Papyrus font)", "The Last Airbender (Live Action)"],
[9.9, 6.1, 2.1]
)
print(zipped)
# {
# 'Avatar: The Last Airbender': 9.9,
# 'Avatar (in Papyrus font)': 6.1,
# 'The Last Airbender (Live Action)': 2.1,
# }
Here's the pseudocode:
If either the
keys
orvalues
list is empty, return an empty dictionary (base case)Recursively call
zipmap
on all but the first elements fromkeys
andvalues
Add the first element of
keys
to the resulting dictionary, and set its value to the first element invalues
Return the updated dictionary
Assignment
def zipmap(keys, values):
if len(keys) == 0 or len(values) == 0:
return {}
restDict = zipmap(keys[1:], values[1:])
restDict[keys[0]] = values[0]
return restDict
What Does This Function Do?
It zips two lists together into a dictionary!
It takes a list of
keys
and a list ofvalues
.It pairs them up so each key gets a value.
zipmap(["a", "b", "c"], [1, 2, 3])
should return:
{"a": 1, "b": 2, "c": 3}
How Does It Work?
This function builds the dictionary backwards using recursion.
Step 1: Base Case (When to Stop)
if len(keys) == 0 or len(values) == 0:
return {}
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)
restDict = zipmap(keys[1:], values[1:])
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:
zipmap(["c"], [3])
Calls zipmap([], [])
Will add "c": 3 later
Fourth Call (Base Case):
zipmap([], [])
Returns {}
(empty dictionary)
Building Back Up (Returning from Recursive Calls)
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:
{"a": 1, "b": 2, "c": 3}
Last updated