Posted in Python onJuly 31, 2016
字典中的键使用时必须满足一下两个条件:
1、每个键只能对应一个项,也就是说,一键对应多个值时不允许的(列表、元组和其他字典的容器对象除外)。当有键发生冲突时(即字典键重复赋值),取最后的赋值。
>>> 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'} >>>
2、键必须是可哈希的,像列表和字典这样的可变类型,由于他们是不可哈希的,所以不能作为字典的键。
为什么呢?—— 解释器调用哈希函数,根据字典中键的值来计算存储你的数据的位置。如果键是可变对象,可以对键本身进行修改,那么当键发生变化时,哈希函数会映射到不同的地址来存储数据,这样哈希函数就不可能可靠地存储或获取相关的数据; 选择可哈希键的原因就是他们的值不能被改变。摘抄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()
运行结果:
[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
python中的字典使用分享
- Author -
hebedich声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@