Python 字典:键值对

PythonPythonBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

字典是Python中的一种基本数据结构。它们允许你存储键值对,并且经常用于表示现实世界中的对象或概念。在这个挑战中,你将使用字典及其值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) 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-13740{{"Python 字典:键值对"}} python/comments -.-> lab-13740{{"Python 字典:键值对"}} python/lists -.-> lab-13740{{"Python 字典:键值对"}} python/dictionaries -.-> lab-13740{{"Python 字典:键值对"}} python/function_definition -.-> lab-13740{{"Python 字典:键值对"}} python/build_in_functions -.-> lab-13740{{"Python 字典:键值对"}} python/data_collections -.-> lab-13740{{"Python 字典:键值对"}} end

字典的值

你会得到一个扁平字典,你需要创建一个函数,该函数返回字典中所有值的扁平列表。你的任务是实现 values_only(flat_dict) 函数,该函数以扁平字典作为参数,并返回字典中所有值的列表。

要解决这个问题,你可以使用 dict.values() 方法来返回给定字典中的值。然后,你可以使用 list() 函数将结果转换为列表。

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

总结

在这个挑战中,你学习了如何从一个扁平字典中提取所有的值,并将它们作为列表返回。你使用了 dict.values() 方法来获取这些值,然后使用 list() 函数将结果转换为列表。在Python中处理字典时,这是一项很有用的技巧。