Skip to main content

Dictionary 字典

不像序列是由一個範圍內的數字當作索引,dictionary 是由鍵 (key) 來當索引,鍵可以是任何不可變的類型;字串和數字都可以當作鍵。Tuple 也可以當作鍵,如果他們只含有字串、數字或 tuple;若一個 tuple 直接或間接地含有任何可變的物件,它就不能當作鍵。你無法使用 list 當作鍵,因為 list 可以經由索引指派 (index assignment)、切片指派 (slice assignment) 或是像 append() 和 extend() 等 method 被修改。

思考 dictionary 最好的方式是把它想成是一組鍵值對 (key: value pair) 的 set,其中鍵在同一個 dictionary 裡必須是獨一無二的。使用一對大括號可建立一個空的 dictionary:{}。將一串由逗號分隔的鍵值對置於大括號則可初始化字典的鍵值對。這同樣也是字典輸出時的格式。

Key type:

  • Numbers
  • Booleans
  • Strings
  • Tuples

資料集合

dictionary1 = {"keyA":valuea, "keyB":value2, "keyC":value3, "KeyD":value4}

dictionary2 = {"keyA":["value1", "value2"], "keyB":["value3", "value4"]}

搜尋鍵-值

NOTE: Dictionary 如果鍵有重複,新的值會覆蓋舊的。

file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
file_counts["txt"]
# Output: 14

# 鍵有重複時
file_counts = {"jpg":10, "txt":14, "csv":2, "py":23, "txt":99}
file_counts["txt"]
# Output: 99

檢查索引

file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
"jpg" in file_counts
# Output: True

新增元素

file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
file_counts["cfg"] = 8
print(file_counts)
# Output {'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23, 'cfg': 8}

變更指定索引的元素

file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
file_counts["csv"] = 17
print(file_counts)
# Output {'jpg': 10, 'txt': 14, 'csv': 17, 'py': 23}

刪除指定索引的元素

file_counts = {"jpg":10, "txt":14, "csv":2, "py":23, 'cfg':8}
del file_counts["cfg"]
print(file_counts)
# Output {'jpg': 10, 'txt': 14, 'csv': 2, 'py': 23}

Dictionary methodsOperations

    Iteratinglen(dictionary) - Returns the number of items in a dictionary.

    for key, in dictionary - Iterates over each key in a dictionary.

    for key, value in dictionary.items() - Iterates over each key,value pair in a dictionary.

    if key in dictionary - Checks whether a key is in a dictionary.

    dictionary[key] - Accesses a value using the associated key from a dictionary.

    dictionary[key] = value - Sets a value associated with a key.

    del dictionary[key] - Removes a value using the associated key from a dictionary.

    字典使用 for loop 迭代時,預設使用 key 存取 

    file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
    for extension in file_counts:
      print(extension)
    
    # Output
    jpg
    txt
    csv
    py

    Methods

      dictionary.get(key, default) - Returns the value corresponding to a key, or the default value if the specified key is not present.

      dictionary.keys() - Returns a sequence containing the keys in a dictionary.

      dictionary.values() - Returns a sequence containing the values in a dictionary.

      dictionary[key].append(value) - Appends a new value for an existing key.

      dictionary.update(other_dictionary) - Updates a dictionary with the items from another dictionary. Existing entries are updated; new entries are added.

      dictionary.clear() - Deletes all items from a dictionary.

      dictionary.copy() - Makes a copy of a dictionary.

      .item()

      .items()  迭代 dictionary 資料時,可存取 key 與 value。

      file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
      for ext, amount in file_counts.items():
        print("There are {} files with the .{} extension".format(amount, ext))
      
      # Output
      There are 10 files with the .jpg extension
      There are 14 files with the .txt extension
      There are 2 files with the .csv extension
      There are 23 files with the .py extension
      .keys() .values()

      .keys() , .values() 

      file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
      file_counts.keys()   # Return dict_keys(['jpg', 'txt', 'csv', 'py'])
      file_counts.values() # Return dict_values([10, 14, 2, 23])
      file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
      for value in file_counts.values():
        print(value)
      
      # Output
      10
      14
      2
      23

      Set 集合

      當您想要儲存一堆元素,並確定這些元素只出現一次時,就會使用集合(set)。集合(set)的元素也必須是不可變的。您可以將其視為字典 (dictionary) 中沒有關聯值 (value) 的鍵 (key)

      • 符號用大括號
      • 內容必須是唯一值,不可重複;如果提供的元素有重複值,程式不會發生錯誤,set 只會存在一個元素
      • 建立空白 set 要用函式 set() 
      • 資料不是序列,元素之間沒有索引及順序關係
      A = {"jlanksy", "drosas", "nmason"}
      
      # Create an empty set
      B = set()
      
      # set 不會有重複的元素
      basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
      print(basket)                      # show that duplicates have been removed
      # Output: {'orange', 'banana', 'pear', 'apple'}