python中的字典使用分享
字典中的鍵使用時必須滿足一下兩個條件:
1、每個鍵只能對應(yīng)一個項,也就是說,一鍵對應(yīng)多個值時不允許的(列表、元組和其他字典的容器對象除外)。當(dāng)有鍵發(fā)生沖突時(即字典鍵重復(fù)賦值),取最后的賦值。
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'}
>>>
2、鍵必須是可哈希的,像列表和字典這樣的可變類型,由于他們是不可哈希的,所以不能作為字典的鍵。
為什么呢?—— 解釋器調(diào)用哈希函數(shù),根據(jù)字典中鍵的值來計算存儲你的數(shù)據(jù)的位置。如果鍵是可變對象,可以對鍵本身進行修改,那么當(dāng)鍵發(fā)生變化時,哈希函數(shù)會映射到不同的地址來存儲數(shù)據(jù),這樣哈希函數(shù)就不可能可靠地存儲或獲取相關(guān)的數(shù)據(jù); 選擇可哈希鍵的原因就是他們的值不能被改變。摘抄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()
運行結(jié)果:
[root@localhost src]# python usrpw.py (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
相關(guān)文章
python 利用matplotlib在3D空間中繪制平面的案例
這篇文章主要介紹了python 利用matplotlib在3D空間中繪制平面的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
python設(shè)計tcp數(shù)據(jù)包協(xié)議類的例子
今天小編就為大家分享一篇python設(shè)計tcp數(shù)據(jù)包協(xié)議類的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
如何通過神經(jīng)網(wǎng)絡(luò)實現(xiàn)線性回歸的擬合
這篇文章主要介紹了如何通過神經(jīng)網(wǎng)絡(luò)實現(xiàn)線性回歸的擬合問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

