Dictionary in Liste

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. Manchmal müssen wir ein Dictionary in eine Liste von Tupeln umwandeln. In dieser Herausforderung haben Sie die Aufgabe, eine Funktion zu schreiben, die ein Dictionary als Argument nimmt und eine Liste von Tupeln zurückgibt.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") 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-13620{{"Dictionary in Liste"}} python/comments -.-> lab-13620{{"Dictionary in Liste"}} python/lists -.-> lab-13620{{"Dictionary in Liste"}} python/tuples -.-> lab-13620{{"Dictionary in Liste"}} python/dictionaries -.-> lab-13620{{"Dictionary in Liste"}} python/function_definition -.-> lab-13620{{"Dictionary in Liste"}} python/build_in_functions -.-> lab-13620{{"Dictionary in Liste"}} python/data_collections -.-> lab-13620{{"Dictionary in Liste"}} end

Dictionary in Liste

Schreiben Sie eine Funktion dict_to_list(d), die ein Dictionary d als Argument nimmt und eine Liste von Tupeln zurückgibt. Jedes Tupel sollte ein Schlüssel-Wert-Paar aus dem Dictionary enthalten. Die Reihenfolge der Tupel in der Liste sollte dieselbe sein wie die Reihenfolge der Schlüssel-Wert-Paare im Dictionary.

def dict_to_list(d):
  return list(d.items())
d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4}
dict_to_list(d)
## [('one', 1), ('three', 3), ('five', 5), ('two', 2), ('four', 4)]

Zusammenfassung

In dieser Herausforderung haben Sie gelernt, wie man in Python ein Dictionary in eine Liste von Tupeln umwandelt. Sie können die dict.items()-Methode verwenden, um eine Liste von Tupeln aus dem Dictionary zu erhalten.