python dict

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章