字典中的键使用时必须满足一下两个条件:
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
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。