Extracting Dictionary Keys in Python

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. Each key is unique and is used to access its corresponding value. Sometimes, we may need to extract only the keys from a dictionary. In this challenge, you are tasked with creating a function that takes a flat dictionary as input and returns a list of all its keys.


Skills Graph

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

Dictionary Keys

Write a function keys_only(flat_dict) that takes a flat dictionary as input and returns a list of all its keys.

To solve this problem, you can follow these steps:

  1. Use dict.keys() to return the keys in the given dictionary.
  2. Return a list() of the previous result.
def keys_only(flat_dict):
  return list(flat_dict.keys())
ages = {
  'Peter': 10,
  'Isabel': 11,
  'Anna': 9,
}
keys_only(ages) ## ['Peter', 'Isabel', 'Anna']

Summary

In this challenge, you have learned how to extract only the keys from a dictionary in Python. You can use the dict.keys() method to return the keys and then convert the result to a list.