Python Dictionaries: Key-Value Pairs

PythonPythonBeginner
Practice Now

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

Introduction

Dictionaries are a fundamental data structure in Python. They allow you to store key-value pairs and are often used to represent real-world objects or concepts. In this challenge, you will be working with dictionaries and their values.


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/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-13740{{"`Python Dictionaries: Key-Value Pairs`"}} python/variables_data_types -.-> lab-13740{{"`Python Dictionaries: Key-Value Pairs`"}} python/lists -.-> lab-13740{{"`Python Dictionaries: Key-Value Pairs`"}} python/dictionaries -.-> lab-13740{{"`Python Dictionaries: Key-Value Pairs`"}} python/function_definition -.-> lab-13740{{"`Python Dictionaries: Key-Value Pairs`"}} python/data_collections -.-> lab-13740{{"`Python Dictionaries: Key-Value Pairs`"}} python/build_in_functions -.-> lab-13740{{"`Python Dictionaries: Key-Value Pairs`"}} end

Dictionary Values

You are given a flat dictionary, and you need to create a function that returns a flat list of all the values in the dictionary. Your task is to implement the values_only(flat_dict) function, which takes a flat dictionary as an argument and returns a list of all the values in the dictionary.

To solve this problem, you can use the dict.values() method to return the values in the given dictionary. Then, you can convert the result to a list using the list() function.

def values_only(flat_dict):
  return list(flat_dict.values())
ages = {
  'Peter': 10,
  'Isabel': 11,
  'Anna': 9,
}
values_only(ages) ## [10, 11, 9]

Summary

In this challenge, you learned how to extract all the values from a flat dictionary and return them as a list. You used the dict.values() method to get the values and then converted the result to a list using the list() function. This is a useful technique when working with dictionaries in Python.

Other Python Tutorials you may like