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/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) 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{{"Python における辞書のキーの抽出"}} python/comments -.-> lab-13679{{"Python における辞書のキーの抽出"}} python/lists -.-> lab-13679{{"Python における辞書のキーの抽出"}} python/dictionaries -.-> lab-13679{{"Python における辞書のキーの抽出"}} python/function_definition -.-> lab-13679{{"Python における辞書のキーの抽出"}} python/build_in_functions -.-> lab-13679{{"Python における辞書のキーの抽出"}} python/data_collections -.-> lab-13679{{"Python における辞書のキーの抽出"}} end

辞書のキー

入力としてフラットな辞書を受け取り、そのすべてのキーのリストを返す関数 keys_only(flat_dict) を作成します。

この問題を解決するには、次の手順に従うことができます。

  1. dict.keys() を使用して、与えられた辞書のキーを返します。
  2. 前の結果の list() を返します。
def keys_only(flat_dict):
  return list(flat_dict.keys())
ages = {
  'Peter': 10,
  'Isabel': 11,
  'Anna': 9,
}
keys_only(ages) ## ['Peter', 'Isabel', 'Anna']

まとめ

このチャレンジでは、Python の辞書からキーのみを抽出する方法を学びました。辞書のキーを返すには dict.keys() メソッドを使用し、その結果をリストに変換します。