深入理解Python中字典的键的使用
字典的键 字典中的值没有任何限制, 可以是任意Python对象,即从标准对象到用户自定义对象皆可,但是字典中的键是有类型限制的。 >>> dict1 = {'foo':789,'foo': 'xyz'} >>> dict1 {'foo': 'xyz'} >>> dict1['foo'] = 123 >>> dict1 {'foo': 123} (2)键必须是可哈希的 大多数Python对象可以作为键,但它们必须是可哈希的对象。像列表和字典这样的可变类型,由于它们不是可哈希的,所以不能作为键。 示例: #!/usr/bin/env python db = {} def newuser(): prompt= 'please regist your name: ' while True: name = raw_input(prompt) if db.has_key(name): prompt = 'name taken,try another: ' continue else: break pwd = raw_input('passswd: ') db[name] = pwd print 'Newuser [%s] has added successfully!' %name 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: """ while True: try: choice = raw_input(prompt).strip()[0].lower() print 'nYou picked: [%s]' % choice if choice not in 'neq': print 'invalid option,please try again' if choice == 'n': newuser() if choice == 'e': olduser() if choice == 'q': break except(EOFError,KeyboardInterrupt): print 'invalid option,please try again' if __name__ == '__main__': showmenu() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |