36.
37.
38.
39.
40.
字典和列表的不同在于,它的索引可以是任意类型的
>>> haha={'a':1,'b':2,'c':3}
>>> print(haha['a'])
1
>>> print(haha['b'])
2
>>> print(haha['c'])
3
>>> haha['d']=4 #在字典中添加元素
>>> print(haha['d'])
4
>>> print(haha) #输出字典
{'b': 2, 'c': 3, 'd': 4, 'a': 1}
还有这种操作:
>>> haha[1]='sb'
>>> haha[2]='SB'
>>> print(haha)
{1: 'sb', 2: 'SB', 'c': 3, 'b': 2, 'd': 4, 'a': 1}
删除字典中的元素:关键字del
>>> print(haha)
{1: 'sb', 2: 'SB', 'c': 3, 'b': 2, 'd': 4, 'a': 1}
>>> del haha['a']
>>> print(haha)
{1: 'sb', 2: 'SB', 'c': 3, 'b': 2, 'd': 4}
>>> del haha[1]
>>> print(haha)
{2: 'SB', 'c': 3, 'b': 2, 'd': 4}
这是一个重要的例题
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." cities['_find'] = find_city #这里把函数名当做变量,如果这句写在函数之前就会报错 while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break #当没有录入时state为''或者None此时not state为True city_found = cities['_find'](cities, state)
print city_found>>> not ''
True
>>> not 123
False
>>> not'12'
False
>>> not None
True
>>> haha={'a':1,'b':2,'c':3}
>>> 'a' in haha
True