Python:列表与字典3-Routine7

字典:字典的每一项即字典项由一个键(key)和一个值(value)组成,键在冒号左边,值在冒号右边,键是获取值得钥匙,在查找字典中的值时,用的是键,只是唯一能直接从字典中获得值得办法,字典没有位置编号。还有字典不允许通过值来获取键。创建字典的办法是:先输入键,然后是一个冒号,然后是对应这个键的值,字典项之间用逗号隔开,所有字典项用花括号包裹起来,这样就创建了一个字典。
访问字典:1通过键获取值:当得到一个有效的键后,将键放在方括号里放到字典名的后面,就可以访问键所对应的值了。如果试图通过字典中没有的键来访问值,就会产生错误。避免的方法是,在获取值之前先通过in运算符对键进行测试。
2通过get()方法获取值:这种方法有一个内建的安全机制用以处理“通过不存在的键获取值”的情况。如果键不存在就返回默认值,而这个默认值是可以由程序员设置的,如果是缺省状态,当键不存在时,就会返回一个None。它的形式是先是字典名,然后是点号,接下来是get(key,返回值)。

接下来的一个例子将会含有对字典的一些基本操作:获取值,增加键值对,替换键值对和删除键值对。

print("""
           Profashional Dictionary

           choice          function

             1 ------------ Present the dictionary
             2 ------------ Search for a term
             3 ------------ Add a dictionary term
             4 ------------ Redifine a term in dictionary
             5 ------------ Delete a term in dictionary
             0 ------------ Exit



      """)
dic = {"Auger effect":"a physical phenomenon in which the filling of an inner-shell vacancy of an atom"\
"is accompanied by the emission of an electron from the same atom.","Impact ionization":"the process in"\
"a material by which one energetic charge carrier can lose energy by the creation of other charge carriers. "}
choice = None
while choice != '0':
           choice = input("\nYour choice is :")
           if choice == '0':
                      print("\nExiting!")
                      break
           elif choice == '1':
                      print("Word:Meaning\n")
                      #print(dic.items())
                      #print(dic.keys())
                      #print(dic.values())
                      for term in dic:
                                 print(term,":",dic[term])
           elif choice == '2':
                      key = input("\nWhat term do you want to search?:")
                      key = key.capitalize()
                      print(dic.get(key,"Sorry,the term is not in the dictionary!"))
                      #if key in dic:
                                 #print(key,":",dic[key])
                      #else:
                                 #print("Sorry,the",key,"not in the dictionary!")
           elif choice == '3':
                      key = input("\nWhat concept do you want to add?:")
                      key = key.capitalize()
                      if key in dic:
                                 print("It is already in the dictionary.")
                      else:
                                 dic[key] = input("Enter its meaning:")
           elif choice == '4':
                      key = input("\nWhat concept do you want to redifine?:")
                      key = key.capitalize()
                      if key not in dic:
                                 print("It is not yet in the dictionary.")
                      else:
                                 dic[key] = input("Enter the new meaning of the concept:")
           else:
                      key = input("\nWhat concept do you want to delete?:")
                      key = key.capitalize()
                      if key not in dic:
                                 print("It is not in the dictionary.")
                      else:
                                 del dic[key]
print("\nNow the dictionary is:\nWord:Meaning")
for term in dic:
           print(term,":",dic[term])
input("\nPress the enter key to quit!")


部分字典方法
get(key,[default]) :返回key值。如果可以不存在,就返回(可选的)default。如果key不存在,且未指定default,则返回None。
key() :返回字典中所有键的视图。
value():返回字典中所有值的视图
items():返回字典中所有字典项的视图。每个字典项都是一个两元素元组,其中第一个元素是键,第二个元素是键所对应的值。

#Blood Game
#
#计算机从一组单词表中随机选出一个单词,玩家要在血量流尽完猜中那个单词
#玩家一共有7点血量,每猜错一次就丢失一点血量。
DIC = ("KID","SUN","BLOOD","SCHOOL","BEAUTY")
BLOOD = (
         """■■■■■■■""",
         """■■■■■■""",
         """■■■■■""",
         """■■■■""",
         """■■■""",
         """■■""",
         """■""",
         """□""")
import random
WORD = random.choice(DIC)
wrong = 0
so_far = '*'*len(WORD)
used = []
print("\nNow your blood point is:",end = " ")
print(BLOOD[wrong])
while wrong < 7:
           print("So far the word is:",so_far)
           letter = input("\nEnter the letter you guess:")
           new = ""
           if letter.upper() in WORD:
                      for i in range(len(WORD)):
                                 if letter.upper() == WORD[i]:
                                            new += WORD[i]
                                 else:
                                            new += so_far[i]
                      so_far = new

           else:
                      wrong += 1
                      print("Sorry,the letter is not in the word.")
                      print("The blood point is",end = " ")
                      print(BLOOD[wrong])
           if new.strip() == WORD:
                      print("You guess it!The word is:",WORD)                      
                      break
           used.append(letter)
           print("Up to now the letters you have used are listed:",used)
if wrong == 7:
           print("You have no blood to play this game:",BLOOD[wrong])
input("\nPress the enter key to end this game!")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值