Skip to content

🐍 Program 138: Convert Dictionary to List of Tuples #161

@iamAntimPal

Description

@iamAntimPal

🐍 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 QuestionsenhancementNew feature or requestquestionFurther information is requested

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions