Umwandlung von Listen von Tupeln in Dictionaries
Ein Dictionary ist eine Sammlung, die ungeordnet, veränderlich und indiziert ist. In Python werden Dictionaries mit geschweiften Klammern geschrieben und haben Schlüssel und Werte.
Die dict()
-Funktion kann verwendet werden, um eine Liste von Tupeln in ein Dictionary umzuwandeln, wobei das erste Element jedes Tupels der Schlüssel und das zweite Element der Wert ist.
## Beispiel 1:
x = [("a", 1), ("b", 2), ("c", 3)]
y = dict(x)
print(y) ## gibt {"a": 1, "b": 2, "c": 3} aus
print(type(y)) ## gibt <class 'dict'> aus
## Beispiel 2:
x = [("fruit", "apple"), ("color", "red")]
y = dict(x)
print(y) ## gibt {"fruit": "apple", "color": "red"} aus
print(type(y)) ## gibt <class 'dict'> aus