The keys in the dictionary must meet two conditions when used:
1, each key can only one item, that is, one key for multiple values is not allowed (list, tuple and other dictionary container object except). When a key conflict occurs (that is, the dictionary key is repeated assignment), the last assignment is taken.
>>> myuniversity_dict = {'name':'Yuanyuan',' Age': 18,' Age': 19,' Age': 20,'Schoolname': Chengdu,'Schoolname': Xinxiang} Traceback (most recent): File"<stdin>", Line 1,inch<module>Nameerror:name'Chengdu' is notdefined>>> myuniversity_dict = {'name':'Yuanyuan',' Age': 18,' Age': 19,' Age': 20,'Schoolname':'Chengdu','Schoolname':'Xinxiang'}>>>myuniversity_dict{' Age': 20,'name':'Yuanyuan','Schoolname':'Xinxiang'}>>>
2. Keys must be hashed, such as mutable types such as lists and dictionaries, because they are not hashed, so they cannot be used as keys to the dictionary.
Why is it? --The interpreter calls the hash function to calculate the location where your data is stored, based on the value of the key in the dictionary. If the key is a mutable object, you can modify the key itself, and when the key changes, the hash function maps to a different address to store the data, so that the hash function is not able to reliably store or fetch the relevant data; The reason to choose a hash key is that their value cannot be changed. Excerpt from Python core programming (second edition) is an example of the following:
#!/usr/bin/env pythonDB= {}defNewUser (): Prompt='Login Desired:' whileTrue:name=raw_input (Prompt)ifDb.has_key (name): Prompt='name Taken, try Another\n' Continue Else: Breakpwd= Raw_input ('passwd:') Db[name]=pwddefOlduser (): Name= Raw_input ('Login:') PWD= Raw_input ('passwd:') passwd=db.get (name)ifpasswd = =pwd:Print 'Welcome back', nameElse: Print 'Login Incorrect'defShowMenu (): Prompt="""(N) EW user login (E) xisting user Login (Q) uitenter choice:""" Done=False while notDone:chosen=False while notChosen:Try: Choice=raw_input (Prompt). Strip () [0].lower ()except: Choice='Q' Print '\nyou picked: [%s]'%ChoiceifChoice not inch 'NEQ': Print 'invalid option, try again' Else: Chosen=TrueifChoice = ='Q':d one =TrueifChoice = ='N': NewUser ()ifChoice = ='e': Olduser ()if __name__=='__main__': ShowMenu ()
Operation Result:
[[email protected] src] # 1try another
A dictionary application instance in Python