9-89. The Python Dictionary: Deep Dive
介紹程式易讀性
dictionary = {
key: value,
key: value,
key: value,
}
sample_dictionary = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
key1~key3 可以是不同的資料型態
呼叫方法,給 key 回傳 value
sample_dictionary[index]
sample_dictionary["String_spelling"]
常見錯誤
spelling error
type error
square brackets []
curly braces {}
■ 列印 Dictionary 中的所有值,示範 code
for key in programming_dictionary:
print(key) # 印出 key 的值
print(programming_dictionary[key]) # 印出 Dictionaries 中的所有值,包含 key & value
補充:這兩行和上述程式碼的前兩行,結果一樣
for dictionary in programming_dictionary:
print(dictionary) # 印出 key 的值
9-90. [Interactive Coding Exercise] Grading Program
沒什麼
9-91. Nesting Lists and Dictionaries
nested_dictionary = {
key1: [List],
key2: {dictionary},
}
■ You could also just nest 【a list in a list】.
but it’s not quite as useful as nesting 【a list in a dictionary】 or 【a dictionary in a dictionary】
because the way that data is structured.
Quiz 7: Python Dictionaries Quiz
Question 2:
dict = {
"a": 1,
"b": 2,
"c": 3,
}
Which line of code will produce an error?
• dict["c"] = [1,2,3] # This will change the last key value pair to hold a List. It's valid to have mixed Types in the dictionary's values.
• for key in dict: # This will add 1 to each of the values in the dictionary.
dict[key] += 1
• dict[1] = 4 # This line of code will add a new key value pair {1: 4}.
• print(dict[1]) # There is no key that matches 1, this will give you a KeyError.
9-93. The Secret Auction Program Instructions and Flow Chart
9-94. Solution and Complete Code for the Secret Auction Program
9-95. Motivation and the Accountability Trick
沒什麼