Tutorialspoint
Problem
Solution
Submissions

Convert a Dictionary to a List of Tuples

Certification: Intermediate Level Accuracy: 100% Submissions: 1 Points: 5

Write a Python program that converts a dictionary into a list of tuples, where each tuple contains a key-value pair.

Example 1
  • Input: {'a': 1, 'b': 2, 'c': 3}
  • Output: [('a', 1), ('b', 2), ('c', 3)]
  • Explanation:
    • Step 1: Take the input dictionary {'a': 1, 'b': 2, 'c': 3}.
    • Step 2: For each key-value pair in the dictionary, create a tuple (key, value).
    • Step 3: Add each tuple to a list.
    • Step 4: Return the list of tuples [('a', 1), ('b', 2), ('c', 3)].
Example 2
  • Input: {'x': 5, 'y': 2, 'z': 8}
  • Output: [('x', 5), ('y', 2), ('z', 8)]
  • Explanation:
    • Step 1: Take the input dictionary {'x': 5, 'y': 2, 'z': 8}.
    • Step 2: For each key-value pair in the dictionary, create a tuple (key, value).
    • Step 3: Add each tuple to a list.
    • Step 4: Return the list of tuples [('x', 5), ('y', 2), ('z', 8)].
Constraints
  • 1 ≤ len(d) ≤ 10^3
  • -10^5 ≤ d[key] ≤ 10^5
  • Time Complexity: O(n), where n is the number of key-value pairs
  • Space Complexity: O(n)
TupleDictionaries Goldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the items() method to get key-value pairs from the dictionary.
  • Convert the result of items() directly into a list.
  • Alternatively, use a list comprehension to create the list of tuples.

Steps to solve by this approach:

 Step 1: Access the items() method of the dictionary.
 Step 2: The items() method returns a view object of (key, value) tuples.
 Step 3: Convert this view object to a list using the list() constructor.
 Step 4: This creates a list where each element is a tuple of (key, value).
 Step 5: The order in Python 3.7+ dictionaries is insertion order.
 Step 6: Return the created list of tuples.
 Step 7: Example: {'a': 1, 'b': 2, 'c': 3} becomes [('a', 1), ('b', 2), ('c', 3)].

Submitted Code :