Algorithm
Input:
- Two lists, list1 and list2
Output:
- A dictionary created from the elements of the two lists
Steps:
1. Initialize an empty dictionary, let's call it 'result_dict'.
2. Check if the lengths of list1 and list2 are the same.
- If not, return an error or handle the mismatch appropriately.
3. Iterate through the indices of the lists using a loop.
a. For each index 'i':
- Extract the element at index 'i' from list1 and list2.
- Create a key-value pair in 'result_dict' using the element from list1 as the key and the element from list2 as the value.
4. After the loop, 'result_dict' will contain the mapping of list1 elements to list2 elements.
Example:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
result_dict = {}
for i in range(len(list1)):
key = list1[i]
value = list2[i]
result_dict[key] = value
# The resulting dictionary will be {'a': 1, 'b': 2, 'c': 3}
Code Examples
#1 Code Example- Python Programing Using zip and dict methods
Code -
Python Programming
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = dict(zip(index, languages))
print(dictionary)
Copy The Code &
Try With Live Editor
Output
#2 Code Example- Python Programing Using list comprehension
Code -
Python Programming
index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = {k: v for k, v in zip(index, languages)}
print(dictionary)
Copy The Code &
Try With Live Editor
Output
Demonstration
Python Programing Example to Convert Two Lists Into a Dictionary-DevsEnv