We are given two list and we need to map key to values of another list so that it becomes dictionary. For example, we are given two list k = ['a', 'b', 'c'] and v = [1, 2, 3] we need to map the keys of list k to the values of list v so that the resultant output should be {'a': 1, 'b': 2, 'c': 3}.
Using zip()
zip() function pairs elements from two lists allowing us to create a dictionary using dict(zip(keys, values)) where each key gets mapped to its corresponding value.
k = ['a', 'b', 'c']
v = [1, 2, 3]
d = dict(zip(k, v))
print(d)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- zip(k, v) function pairs elements from lists k and v into tuples and dict() converts these tuples into key-value pairs in dictionary d.
- Resulting dictionary d is {'a': 1, 'b': 2, 'c': 3}, where each key from k is mapped to its corresponding value in v.
Using Dictionary Comprehension
Dictionary comprehension iterates through the indices of key list and maps each key to its corresponding value from value list.
k = ['a', 'b', 'c']
v = [1, 2, 3]
d = {k[i]: v[i] for i in range(len(k))}
print(d)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- This dictionary comprehension iterates over indices of the k list and assigns each key from k to its corresponding value from v using k[i]: v[i].
- It ensures that mapping is created efficiently without requiring external functions making it a straightforward approach when both lists have same length.
Using dict.fromkeys()
dict.fromkeys(k, v) creates a dictionary where all keys in k are mapped to the same single value v, not individual values from list. It is useful when assigning a default value to multiple keys.
k = ['a', 'b', 'c']
d = 0
d = dict.fromkeys(k, d)
print(d)
Output
{'a': 0, 'b': 0, 'c': 0}
Explanation: dict.fromkeys(k, d) creates a dictionary where each key from the list k is assigned the same value d (which is 0 in this case).
Using map() and dict()
zip(k, v) function pairs corresponding elements from the key and value lists, which map() processes into key-value tuples dict() function then converts these tuples into a dictionary effectively mapping keys to values.
k = ['a', 'b', 'c']
v = [1, 2, 3]
d = dict(map(lambda k, v: (k, v), k, v))
print(d)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- map() function pairs each key in k with its corresponding value in v using a lambda function.
- dict() function then converts the mapped pairs into a dictionary.
Related Article: