Prüfen, ob ein Schlüssel in einem Dictionary existiert

PythonPythonBeginner
Jetzt üben

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

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Einführung

In Python ist ein Dictionary eine Sammlung von Schlüssel-Wert-Paaren. Jeder Schlüssel ist einzigartig und wird verwendet, um auf seinen entsprechenden Wert zuzugreifen. In dieser Herausforderung werden Sie eine Funktion schreiben, die überprüft, ob ein gegebener Schlüssel in einem Dictionary existiert.


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/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/booleans -.-> lab-13676{{"Prüfen, ob ein Schlüssel in einem Dictionary existiert"}} python/comments -.-> lab-13676{{"Prüfen, ob ein Schlüssel in einem Dictionary existiert"}} python/tuples -.-> lab-13676{{"Prüfen, ob ein Schlüssel in einem Dictionary existiert"}} python/dictionaries -.-> lab-13676{{"Prüfen, ob ein Schlüssel in einem Dictionary existiert"}} python/function_definition -.-> lab-13676{{"Prüfen, ob ein Schlüssel in einem Dictionary existiert"}} end

Prüfen, ob ein Schlüssel in einem Dictionary existiert

Schreiben Sie eine Funktion key_in_dict(d, key), die ein Dictionary d und einen Schlüssel key als Argumente übernimmt und True zurückgibt, wenn der Schlüssel im Dictionary existiert, andernfalls False.

def key_in_dict(d, key):
  return (key in d)
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
key_in_dict(d, 'three') ## True

Zusammenfassung

In dieser Herausforderung haben Sie gelernt, wie Sie in Python überprüfen, ob ein Schlüssel in einem Dictionary existiert. Sie können den in-Operator verwenden, um zu überprüfen, ob ein Dictionary einen bestimmten Schlüssel enthält.