为了账号安全,请及时绑定邮箱和手机立即绑定

python dict

标签:
Python

不以数字为索引值来检索存储的数据,以”键(key)"来作为索引
要让变量成为字典,只要使用{}  大括号或设置为dict()函数
keywords={} 或 keywords=dict(),keywords就变成了字典dict 类型
\>>> keywords={}
\>>> keywords['book']=10
\>>> keywords['campus']=15
\>>> keywords['cook']=9
\>>> keywords['Python']=26
\>>> type(keywords)
<type 'dict'>
\>>> keywords['Python']
26
\>>> keywords
{'cook': 9, 'Python': 26, 'book': 10, 'campus': 15}
\>>> keywords.keys()
['cook', 'Python', 'book', 'campus']
\>>> keywords.values()
[9, 26, 10, 15]
\>>>

方法使用                     运算结果说明
d.clear()       清除字典d的所有内容
d1=d.copy() 把d的内容复制一份给d1
d.get(key)  通过key取出相对应的value
d.items()       返回dict_items格式的字典的所有内容
d.keys()        以dict_items格式列出字典所有d的所有键
d.update(d2)    使用d2的内容去更新d相同的键值
d.values()      以dict_items的格式列出字典d的所有值

\>>> dict1={'google':'www.google.com','sina':'www.sina.com'}
\>>> dict1.items()
[('google', 'www.google.com'), ('sina', 'www.sina.com')]
\>>> for key,values in dict1.items():
...   print key,values
...
google www.google.com
sina www.sina.com
\>>>
\>>> dict1.keys()
['google', 'sina']
\>>> dict1.values()
['www.google.com', 'www.sina.com']
\>>> dict1.get('sina')
'www.sina.com'
\>>> len(dict1)
2
\>>> max(dict1)
'sina'
\>>> min(dict1)
'google'
\>>>
\>>> dict2={'taobao':'www.taobao.com'}
\>>> dict1.update(dict2)
\>>> dict1.items()
[('google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('sina', 'www.sina.com')]
\>>> dict3={'sina':'www.sina.cn'}
\>>> dict1.update(dict3)
\>>> dict1
{'google': 'www.google.com', 'taobao': 'www.taobao.com', 'sina': 'www.sina.cn'}
\>>>
\>>> dict1
{'google': 'www.google.com', 'taobao': 'www.taobao.com', 'sina': 'www.sina.cn'}
\>>> for key in dict1.keys():
...    print key ,dict1.get(key)
...
google www.google.com
taobao www.taobao.com
sina www.sina.cn
\>>> for value in dict1.values():
...    print value
...
www.google.com
www.taobao.com
www.sina.cn

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消