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

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