Słownik Pythona setdefault() Metoda
Przykład
Uzyskaj wartość pozycji „model”:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
Definicja i użycie
Metoda setdefault()
zwraca wartość elementu z określonym kluczem.
Jeśli klucz nie istnieje, włóż klucz o określonej wartości, patrz przykład poniżej
Składnia
dictionary.setdefault(keyname, value)
Wartości parametrów
Parameter | Description |
---|---|
keyname | Required. The keyname of the item you want to return the value from |
value | Optional. If the key exist, this parameter has no effect. If the key does not exist, this value becomes the key's value Default value None |
Więcej przykładów
Przykład
Pobierz wartość elementu „kolor”, jeśli element „kolor” nie istnieje, wstaw „kolor” z wartością „biały”:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color",
"white")
print(x)