第一,一鍵一項。一個鍵對應多個值是不允許的(列表、元組、其他字典等容器對象作為值除外)。鍵重複賦值時,取最後一次。
>>> myuniversity_dict = {'name':'yuanyuan', 'age':18, 'age':19, 'age':20,
... 'schoolname':Chengdu, 'schoolname':Xinxiang}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Chengdu' is not defined
>>> myuniversity_dict = {'name':'yuanyuan', 'age':18, 'age':19, 'age':20,
... 'schoolname':'Chengdu', 'schoolname':'Xinxiang'}
>>> myuniversity_dict
{'age': 20, 'name': 'yuanyuan', 'schoolname': 'Xinxiang'}
順帶說明:字符串必須加引號,否則解釋器會當成變量名去查找。
第二,鍵必須可哈希。列表、字典這類可變對象不可哈希,因此不能作為鍵。
原因在於查找機制:解釋器調用哈希函數,根據鍵的值計算數據存放位置。若鍵是可變對象,鍵本身一旦改變,哈希函數就會映射到另一個地址,此後既存不進也取不出原數據。要求鍵不可變,正是為了讓哈希值穩定可靠。
以下示例(改寫自《Python 核心編程(第二版)》)用字典存儲用戶名與口令:
#!/usr/bin/env python
db = {}
def newuser():
prompt = 'login desired: '
while True:
name = raw_input(prompt)
if db.has_key(name):
prompt = 'name taken, try another\n'
continue
else:
break
pwd = raw_input('passwd: ')
db[name] = pwd
def olduser():
name = raw_input('login: ')
pwd = raw_input('passwd: ')
passwd = db.get(name)
if passwd == pwd:
print 'welcome back', name
else:
print 'login incorrect'
def showmenu():
prompt = """
(N)ew User Login
(E)xisting User Login
(Q)uit
Enter choice:"""
done = False
while not done:
chosen = False
while not chosen:
try:
choice = raw_input(prompt).strip()[0].lower()
except:
choice = 'q'
print '\nYou picked: [%s]' % choice
if choice not in 'neq':
print 'invalid option, try again'
else:
chosen = True
if choice == 'q': done = True
if choice == 'n': newuser()
if choice == 'e': olduser()
if __name__ == '__main__':
showmenu()
運行效果:
(N)ew User Login (E)xisting User Login (Q)uit Enter choice:n You picked: [n] login desired: root passwd: 1 (N)ew User Login (E)xisting User Login (Q)uit Enter choice:n You picked: [n] login desired: root name taken, try another
這個例子把字典的兩個核心操作都用上了:has_key() 判斷鍵是否存在(重名則要求換一個),get() 在鍵缺失時返回 None 而不拋 KeyError,讓登錄校驗可以安全地走到「口令錯誤」分支。
補充說明:示例基於 Python 2 語法(raw_input、print 語句、has_key)。在 Python 3 中,對應寫法分別是 input()、print() 函數,以及 name in db。