1.只有不可变的数据类型才能作为键值:
>>> 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'}
>>>