-
-
Notifications
You must be signed in to change notification settings - Fork 5
Open
Labels
PythonPython Interview QuestionsPython Interview QuestionsenhancementNew feature or requestNew feature or requestquestionFurther information is requestedFurther information is requested
Milestone
Description
🐍 Program 138: Convert Dictionary to List of Tuples
📌 Description
Write a function that converts a dictionary into a list of key-value tuples. The elements in the list should be in alphabetical order based on the keys.
💡 Code Example
def dict_to_list(d):
# Sort the dictionary by key and return the list of tuples
return sorted(d.items())
# Examples
print(dict_to_list({
"D": 1,
"B": 2,
"C": 3
})) # ➞ [("B", 2), ("C", 3), ("D", 1)]
print(dict_to_list({
"likes": 2,
"dislikes": 3,
"followers": 10
})) # ➞ [("dislikes", 3), ("followers", 10), ("likes", 2)]✅ Output
[('B', 2), ('C', 3), ('D', 1)]
[('dislikes', 3), ('followers', 10), ('likes', 2)]
🧠 Explanation
- The function uses the
items()method to get the dictionary items as key-value pairs. sorted()is used to sort these pairs alphabetically by key, and the sorted list is returned.
Metadata
Metadata
Assignees
Labels
PythonPython Interview QuestionsPython Interview QuestionsenhancementNew feature or requestNew feature or requestquestionFurther information is requestedFurther information is requested