### 定義及應用
Python內置了字典:dict的支持,dict全稱dictionary,在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度。
### 定義
~~~
stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}#key:value pairs
~~~
### 詞典的常用方法
print dic.keys()?????????? # 返回dic所有的鍵
print dic.values()???????? # 返回dic所有的值
print dic.items()????????? # 返回dic所有的元素(鍵值對)
dic.clear()??????????????? # 清空dic,dict變為{}
del dic['tom'] ? ? ? ? ? ? ?# 刪除 dic 的‘tom’元素
print(len(dic))
dict.get(key,default=None) 對字典dict 中的鍵key,返回它對應的值value,如果字典中不存在此鍵,則返回default 的值(注意,參數default 的默認值為None)
dict.has_key(key) 如果鍵(key)在字典中存在,返回True,否則返回False. 在Python2.2版本引入in 和not in 后,此方法幾乎已廢棄不用了,但仍提供一個 可工作的接口。
dict.keys() 返回一個包含字典中鍵的列表
dict.values() 返回一個包含字典中所有值的列表
### 實例
~~~
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']
# print some states
print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']
# do it by using the state then cities dict
print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]
# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
# print every city in state
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
print "%s state is abbreviated %s and has city %s" % (
state, abbrev, cities[abbrev])
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas', None)
if not state:
print "Sorry, no Texas."
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')#if exist key=='TX',city=value,or city='Dose Not Exist'
print "The city for the state 'TX' is: %s" % city
~~~
output
~~~
----------
NY State has: New York
OR State has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
----------
FL has the city Jacksonville
CA has the city San Francisco
MI has the city Detroit
OR has the city Portland
NY has the city New York
----------
California state is abbreviated CA and has city San Francisco
Michigan state is abbreviated MI and has city Detroit
New York state is abbreviated NY and has city New York
Florida state is abbreviated FL and has city Jacksonville
Oregon state is abbreviated OR and has city Portland
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist
~~~
和list比較,dict有以下幾個特點:
1. 查找和插入的速度極快,不會隨著key的增加而增加;
1. 需要占用大量的內存,內存浪費多。
所以,dict是用空間來換取時間的一種方法。
dict可以用在需要高速查找的很多地方,在Python代碼中幾乎無處不在,正確使用dict非常重要,**需要牢記的第一條就是dict的key必須是**不可變對象**。這是因為dict根據key來計算value的存儲位置,如果每次計算相同的key得出的結果不同,那dict內部就完全混亂了。