طريقة تعيين قاموس Python الافتراضي ()
مثال
احصل على قيمة عنصر "النموذج":
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
التعريف والاستخدام
تقوم setdefault()
الطريقة بإرجاع قيمة العنصر بالمفتاح المحدد.
إذا كان المفتاح غير موجود ، أدخل المفتاح بالقيمة المحددة ، انظر المثال أدناه
بناء الجملة
dictionary.setdefault(keyname, value)
قيمه المعامل
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 |
مزيد من الأمثلة
مثال
احصل على قيمة عنصر "color" ، إذا كان عنصر "color" غير موجود ، أدخل "color" بالقيمة "white":
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("color",
"white")
print(x)