
Problem
Solution
Submissions
Convert a List of Tuples into a Dictionary
Certification: Basic Level
Accuracy: 91.43%
Submissions: 35
Points: 10
Write a Python program that converts a list of tuples into a dictionary. Each tuple consists of two elements: the first element becomes a key in the dictionary, and the second element becomes its corresponding value.
Example 1
- Input: tuple_list = [("a", 1), ("b", 2), ("c", 3)]
- Output: {"a": 1, "b": 2, "c": 3}
- Explanation:
- Step 1: Initialize an empty dictionary.
- Step 2: Iterate through each tuple in the input list.
- Step 3: For each tuple, use the first element as a key and the second element as its value in the dictionary.
- Step 4: For ("a", 1), set key "a" to value 1.
- Step 5: For ("b", 2), set key "b" to value 2.
- Step 6: For ("c", 3), set key "c" to value 3.
- Step 7: Return the resulting dictionary.
Example 2
- Input: tuple_list = [("apple", 5), ("banana", 7), ("orange", 8), ("apple", 10)]
- Output: {"apple": 10, "banana": 7, "orange": 8}
- Explanation:
- Step 1: Initialize an empty dictionary.
- Step 2: Iterate through each tuple in the input list.
- Step 3: For each tuple, use the first element as a key and the second element as its value in the dictionary.
- Step 4: For ("apple", 5), set key "apple" to value 5.
- Step 5: For ("banana", 7), set key "banana" to value 7.
- Step 6: For ("orange", 8), set key "orange" to value 8.
- Step 7: For ("apple", 10), update key "apple" to value 10 (overwriting the previous value).
- Step 8: Return the resulting dictionary.
Constraints
- 1 ≤ len(tuple_list) ≤ 10^5
- All keys must be hashable
- If there are duplicate keys, the last occurrence's value should be used
- Time Complexity: O(n) where n is the number of tuples
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a dictionary comprehension: {key: value for key, value in tuple_list}
- Iterate through the list and update the dictionary for each tuple
- Check if the dictionary already contains a key before adding it
- If the key already exists, update its value
- Use the dict() constructor with the list of tuples: dict(tuple_list)
- Handle edge cases such as empty lists or tuples with more than two elements