Dictionary to List | Challenge

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, a dictionary is a collection of key-value pairs. Sometimes, we may need to convert a dictionary to a list of tuples. In this challenge, you are tasked with writing a function that takes a dictionary as an argument and returns a list of tuples.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/variables_data_types -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/lists -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/tuples -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/dictionaries -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/function_definition -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/data_collections -.-> lab-13088{{"`Dictionary to List | Challenge`"}} python/build_in_functions -.-> lab-13088{{"`Dictionary to List | Challenge`"}} end

Dictionary to List

Problem

Write a function dict_to_list(d) that takes a dictionary d as an argument and returns a list of tuples. Each tuple should contain a key-value pair from the dictionary. The order of the tuples in the list should be the same as the order of the key-value pairs in the dictionary.

Example

d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
dict_to_list(d)
## [('one', 1), ('three', 3), ('five', 5), ('two', 2), ('four', 4)]

Summary

In this challenge, you learned how to convert a dictionary to a list of tuples in Python. You can use the dict.items() method to get a list of tuples from the dictionary.

Other Python Tutorials you may like