习题 40: 字典, 可爱的字典

接下来我要教你另外一种让你伤脑筋的容器型数据结构,因为一旦你学会这种容器,你将拥有超酷的能力。这是最有用的容器:字典(dictionary)。

Python 将这种数据类型叫做 “dict”,有的语言里它的名称是 “hash”。这两种名字我都会用到,不过这并不重要,重要的是它们和列表的区别。你看,针对列表你可以做这样的事情:

>>> things = ['a', 'b', 'c', 'd']
>>> print things[1]
b
>>> things[1] = 'z'
>>> print things[1]
z
>>> print things
['a', 'z', 'c', 'd']
>>>

你可以使用数字作为列表的索引,也就是你可以通过数字找到列表中的元素。而 dict 所作的,是让你可以通过任何东西找到元素,不只是数字。是的,字典可以将一个物件和另外一个东西关联,不管它们的类型是什么,我们来看看:

>>> stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}
>>> print stuff['name']
Zed
>>> print stuff['age']
36
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco
>>>

你将看到除了通过数字以外,我们还可以用字符串来从字典中获取 stuff ,我们还可以用字符串来往字典中添加元素。当然它支持的不只有字符串,我们还可以做这样的事情:

>>> stuff[1] = "Wow"
>>> stuff[2] = "Neato"
>>> print stuff[1]
Wow
>>> print stuff[2]
Neato
>>> print stuff
{'city': 'San Francisco', 2: 'Neato',
    'name': 'Zed', 1: 'Wow', 'age': 36,
    'height': 74}
>>>

在这里我使用了两个数字。其实我可以使用任何东西,不过这么说并不准确,不过你先这么理解就行了。

当然了,一个只能放东西进去的字典是没啥意思的,所以我们还要有删除物件的方法,也就是使用 del 这个关键字:

>>> del stuff['city']
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{'name': 'Zed', 'age': 36, 'height': 74}
>>>

接下来我们要做一个练习,你必须非常仔细,我要求你将这个练习写下来,然后试着弄懂它做了些什么。这个练习很有趣,做完以后你可能会有豁然开朗的感觉。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cities = {'CA': 'San Francisco', 'MI': 'Detroit',
                     'FL': 'Jacksonville'}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city(themap, state):
    if state in themap:
        return themap[state]
    else:
        return "Not found."

# ok pay attention!
cities['_find'] = find_city

while True:
    print "State? (ENTER to quit)",
    state = raw_input("> ")

    if not state: break

    # this line is the most important ever! study!
    city_found = cities['_find'](cities, state)
    print city_found

Warning

注意到我用了 themap 而不是 map 了吧?这是因为 Python 已经有一个函数称作 map 了,所以如果你用 map 做变量名,你后面可能会碰到问题。

你应该看到的结果

$ python ex40.py 
State? (ENTER to quit) > CA
San Francisco
State? (ENTER to quit) > FL
Jacksonville
State? (ENTER to quit) > O
Not found.
State? (ENTER to quit) > OR
Portland
State? (ENTER to quit) > VT
Not found.
State? (ENTER to quit) >

加分习题

  1. 在 Python 文档中找到 dictionary (又被称作 dicts, dict)的相关的内容,学着对 dict 做更多的操作。
  2. 找出一些 dict 无法做到的事情。例如比较重要的一个就是 dict 的内容是无序的,你可以检查一下看看是否真是这样。
  3. 试着把 for-loop 执行到 dict 上面,然后试着在 for-loop 中使用 dict 的 items() 函数,看看会有什么样的结果。

Project Versions

Table Of Contents

Previous topic

习题 39: 列表的操作

Next topic

习题 41: 来自 Percal 25 号行星的哥顿人(Gothons)

This Page