Python-Wörterbuch fromkeys()-Methode

Python 字典Python-Wörterbuch


Beschreibung

Die Python-Dictionary-Funktion fromkeys() wird verwendet, um ein neues Dictionary zu erstellen, wobei die SequenzseqElemente in [der Sequenz] als Schlüssel des Dictionaries undvalueals Anfangswert für alle Schlüssel des Dictionaries verwendet werden.

Syntax

Syntax der fromkeys()-Methode:

dict.fromkeys(seq[, value])

Parameters

  • seq -- Liste der Dictionary-Schlüssel.
  • value -- Optionaler Parameter, legt den Wert der Schlüsselsequenz (seq) fest, Standardwert ist None.

Rückgabewert

Diese Methode gibt ein neues Dictionary zurück.

Beispiel

Das folgende Beispiel demonstriert die Verwendung der fromkeys()-Funktion:

Beispiel (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- seq = ('Google', 'Beispiel', 'Taobao') # Standard-Schlüsselwert nicht angeben, Standard ist None thisdict = dict.fromkeys(seq) print ("Neues Dictionary ist: %s" % str(thisdict)) # Standard-Schlüsselwert angeben thisdict = dict.fromkeys(seq, 10) print ("Neues Dictionary ist: %s" % str(thisdict))

Die Ausgabe des obigen Beispiels ist:

新字典为 : {'Google': None, 'Taobao': None, 'Example': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Example': 10}

Python 字典Python-Wörterbuch

Andere Erweiterungen