te40

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
	
  1. 17行的if 语句的判断条件很神奇  not state 只要state 的 值不是ENTER 就不会break
  2. dictionary 还是很像一个list 不过 没有顺序  key必须是常量  有大量函数  
  3. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值