Wednesday, 22 January 2025

Day 97: Python Program to Map Two Lists into a Dictionary


 

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

Popular Posts

Categories

100 Python Programs for Beginner (93) AI (37) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (184) C (77) C# (12) C++ (83) Course (67) Coursera (234) Cybersecurity (24) Data Analytics (2) data management (11) Data Science (135) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Euron (22) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (5) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (65) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (961) Python Coding Challenge (406) Python Quiz (59) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses