cities = {'CA':'san fransico', '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?"
state = raw_input(">")
if not state: break
# this line is the most important
city_found =cities['_find'](cities,state)
print city_found
- 17行的if 语句的判断条件很神奇 not state 只要state 的 值不是ENTER 就不会break
- dictionary 还是很像一个list 不过 没有顺序 key必须是常量 有大量函数
- http://www.runoob.com/python/python-dictionary.html
# 字典创建 while开关 字典添加 字典寻找
dictionary = {}
flag = 'a'
pape = 'a'
off = 'a'
while flag == 'a' or 'c' :
flag = raw_input("添加或查找单词 ?(a/c)")
if flag == "a" : # 开启
word = raw_input("输入单词(key):")
defintion = raw_input("输入定义值(value):")
dictionary[str(word)] = str(defintion) # 添加字典
print "添加成功!"
pape = raw_input("您是否要查找字典?(a/0)") #read
if pape == 'a':
print dictionary
else :
continue
elif flag == 'c':
check_word = raw_input("要查找的单词:") # 检索
for key in sorted(dictionary.keys()): # yes
if str(check_word) == key:
print "该单词存在! " ,key, dictionary[key]
break
else: # no
off = 'b'
if off == 'b':
print "抱歉,该值不存在!"
else: # 停止
print "error type"
break
测试输入:
添加或查找单词 ?(a/c)a
输入单词(key):runoob
输入定义值(value):www.runoob.com
添加成功!
您是否要查找字典?(a/0)0
添加或查找单词 ?(a/c)c
要查找的单词:runoob
该单词存在! runoob www.runoob.com
添加或查找单词 ?(a/c)
用for在 dictionary中取值
for key,values in dict.items():
print key,values