keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4,]
mapped_dict = dict(zip(keys, values))
print("Mapped Dictionary:", mapped_dict)
#source code --> clcoding.com
Code Explanation:
Define Lists of Keys and Values:
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]
keys is a list of strings representing the keys of the dictionary.
values is a list of integers representing the values to be mapped to those keys.
Combine Keys and Values Using zip():
mapped_dict = dict(zip(keys, values))
zip(keys, values): The zip() function pairs each element from the keys list with the corresponding element in the values list, forming an iterable of tuples: [('a', 1), ('b', 2), ('c', 3), ('d', 4)].
dict(zip(keys, values)): The dict() constructor takes this iterable of key-value pairs and creates a dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}.
Print the Result:
print("Mapped Dictionary:", mapped_dict)
This prints the dictionary to the console, showing the final result.
Output:
Mapped Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Key Points:
zip(): Combines two iterables element-wise, creating tuples.
dict(): Converts an iterable of tuples into a dictionary.
Both lists must have the same length; otherwise, zip() will truncate to the shortest list.
0 Comments:
Post a Comment