1. 程式人生 > 實用技巧 >字典(dict)

字典(dict)

1.定義

eng2sp = {}   # 定義空字典
eng2sp['one'] = 'uno'
eng2sp['two'] = 'dos'
print eng2sp
print eng2sp['two']        # 字典查詢:通過key查詢value
eng2sp[2] = 'hdi'          # 字典沒有順序
print eng2sp

2.常見操作

inventory = {'apples': 430, 'bananas': 312,'oranges': 525, 'pears': 217}
# 修改
inventory['bananas'] = 0
print inventory
# 刪除 del inventory['bananas'] print inventory # 計數 print len(inventory) # 清空 inventory.clear() print inventory

3.別名和拷貝

inventory = {'apples': 430, 'bananas': 312,'oranges': 525, 'pears': 217}
alias = inventory
copy1 = inventory.copy()                #alias和inventory指向同一個值。而copy1則指向全新的拷貝
alias['bananas
'] = 33 print inventory['bananas'] #如果修改alias,inventory也發生變化。 copy1['bananas'] = 56 print inventory['bananas'] #如果修改copy1,inventory則不會發生變化。

4.get用法

letterCounts = {}
for letter in "Mississippi":
    letterCounts[letter] = letterCounts.get (letter, 0) + 1
print letterCounts          #
打印出每個字母出現的次數