1.只有不可變的數(shù)據(jù)類型才能作為鍵值:
>>> dic = { [1,2,3]:"abc"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
因此元組可作為鍵值:
>>> dic = { (1,2,3):"abc", 3.1415:"abc"}
>>> dic
{3.1415: 'abc', (1, 2, 3): 'abc'}
2.如果嘗試訪問一個不存在的鍵值码耐,會報錯:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
因此訪問之前可先進行判斷:
>>> if "car" in words: print words["car"]
...
>>> if "cat" in words: print words["cat"]
...
Katze
3.可以通過copy()來復制字典:
[如果不用copy()而是之間a=b這樣來賦值酌泰,則改變a的值會影響b的值,反之亦然]
>>> w = words.copy()
>>> words["cat"]="chat"
>>> print w
{'house': 'Haus', 'cat': 'Katze'}
>>> print words
{'house': 'Haus', 'cat': 'chat'}
>>> w.clear()
>>> print w
{}
4.Update:Merging Dictionaries
>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w1 = {"red":"rouge","blau":"bleu"}
>>> w.update(w1)
>>> print w
{'house': 'Haus', 'blau': 'bleu', 'red': 'rouge', 'cat': 'Katze'}
5,Iterating over a Dictionary
for key in d:
print key
for key in d.iterkeys():
print key
for val in d.itervalues():
print val
for key in d:
print d[key]
5.Connection between Lists and Dictionaries:
5-1.Lists from Dictionaries:
It's possible to create lists frim dictionaries by using the methods items(),keys(),and values(). As the name implies the method keys() creates a list, which consists solely of the keys of the dictionary. values() produces a list consisting of the values. items() can be used to create a list consisting of 2-tuples of (key,value)-pairs:
>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w.items()
[('house', 'Haus'), ('red', 'rot'), ('cat', 'Katze')]
>>> w.keys()
['house', 'red', 'cat']
>>> w.values()
['Haus', 'rot', 'Katze']
5-2:Dictionaries from Lists:
>>> dishes = ["pizza", "sauerkraut", "paella", "Hamburger"]
>>> countries = ["Italy", "Germany", "Spain", "USA"]
>>> country_specialities = zip(countries, dishes)
>>> print country_specialities
[('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'), ('USA', 'Hamburger')]
>>>
The variable country_specialities contains now the "dictionary" in the 2-tuple list form. This form can be easily transformed into a real dictionary with the function dict().
>>> country_specialities_dict = dict(country_specialities)
>>> print country_specialities_dict
{'Germany': 'sauerkraut', 'Spain': 'paella', 'Italy': 'pizza', 'USA': 'Hamburger'}
>>>