QUICK REVIEW 快速復審 <<
Previous Next >> String formatting 字符串格式
MORE ON DICTIONARY KEYS 有關字典鍵的更多信息
Dictionary keys must be unique. If you try to add an element to your dictionary with the same key, it will overwrite the value previously at that key:
字典鍵必須唯一。如果您嘗試使用相同的鍵將元素添加到字典中,它將覆蓋先前在該鍵上的值:
>>> print(price_dictionary["dog food"])
only at Petco
>>> price_dictionary["dog food"] = 10.99
>>> print(price_dictionary["dog food"])
10.99
If you try to ask the dictionary for a key that doesn’t exist, it will throw a KeyError in your console, or your program will crash:
如果您嘗試向字典查詢不存在的鍵,它將KeyError在控制台中拋出a ,否則程序將崩潰:
>>> price_dictionary["lemon"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'lemon'
We will talk about how to “catch” errors in later exercises, but for now, there is another way to make sure you don’t throw an error. Instead of accessing elements in a dictionary with the [] notation, you can instead use the .get() method. As the second argument to .get(), you write down what the default value is for the dictionary: if there is no key like the one you wanted, what the dictionary should return:
我們將在以後的練習中討論如何“捕獲”錯誤,但是目前,還有另一種方法可以確保您不會拋出錯誤。[]您可以使用.get()方法來代替使用符號訪問字典中的元素。作為的第二個參數.get(),您寫下字典的默認值是什麼:如果沒有想要的鍵,則字典應該返回什麼:
>>> print(price_dictionary.get("banana", "no food like this"))
1.50
>>> print(price_dictionary.get("lemon", "no food like this"))
no food like this
This can be a helpful way of avoiding causing your program to crash.
Not all Python objects can be keys to a dictionary. For something to be a key in a dictionary, it must be immutable. Basically, it means that you can’t change that variable somewhere else. So for example, numbers and strings can be keys in a dictionary, but lists cannot. Because you can .append() to a list, it cannot be a key in your dictionary. Lists can be values, just not keys:
這是避免引起程序崩潰的有用方法。
並非所有的Python對像都可以是字典的鍵。為了使某些東西成為字典中的鍵,它必須是不可變的。基本上,這意味著您無法在其他地方更改該變量。因此,例如,數字和字符串可以是字典中的鍵,而列表則不能。因為可以.append()列出,所以它不能成為字典中的鍵。列表可以是值,而不能是鍵:
>>> price_dictionary[[1, 2, 3]] = "new food"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> price_dictionary["lettuce"] = [1.50, 3.50]
>>> print(price_dictionary["lettuce"])
[1.50, 3.50]
Lastly, if we want to check if a particular key is in our dictonary, it is very easy. Just use the in keyword:
最後,如果我們要檢查字典中是否有特定的鍵,這很容易。只需使用in關鍵字:
>>> "lemon" in price_dictionary
False
>>> "banana" in price_dictionary
True
These checks can be used together with if statements to make more complex programs.
這些檢查可以與if語句一起使用以製作更複雜的程序。
QUICK REVIEW 快速復審 <<
Previous Next >> String formatting 字符串格式