继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

python dict

慕仔4209126
关注TA
已关注
手记 304
粉丝 69
获赞 305

不以数字为索引值来检索存储的数据,以”键(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

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP