Example from the third edition of the basic Python tutorial, 57p
This example uses a dictionary to implement a small database that retrieves the user's information by querying the dictionary's key values.
I have modified some of the code.
#!/usr/bin/python3-*-coding:utf-8-*-# Use a dictionary to build a simple database # import module, mainly to do an exception exit import OS # Build people dictionary, used to store user information people = {' A Ilce ': {' phone ': ' 2341 ', ' addr ': ' Foo Drive '}, ' Beth ': {' P Hone ': ' 9102 ', ' addr ': ' Bar Street '}, ' Cecil ': {' phone ': ' 3158 ', ' Addr ': ' Baz Avenue 90 '}}# constructs an output dictionary that is used primarily for later output or not to be built, and to print the time to write the characters up to labels = {' Phone ': ' Phone num ber ', ' addr ': ' Address '}# prompts the user for the first name = input (' name: ') request = input (' Phone number (p) or address (a)? ') # to determine the user data query information, is the address or telephone, here I made the changes. If request = = ' P ': key = ' phone ' elif request = = ' A ': key = ' addr ' else:print (' Your Input Options Erro R. ') Os._exit (1) #异常退出, the following code is not executed. # Determine if the user entered the name in the dictionary, here I made a change. If name in People:print ("{} ' s {} is {}."). Format (Name,labels[key],people[name][key])) Else:print ("sorry.{}" s {} is not existe ". Format (Name,labels[key))
Operation Result:
# 用户不存在的情况下。[[email protected] dict]# python3 phone.py Name:PengPhone number(p) or address(a)?aSorry.Peng‘s address is not existe#用户存在的情况下[[email protected] dict]# python3 phone.py Name:Cecil Phone number(p) or address(a)?pCecil‘s phone number is 3158.[[email protected] dict]# python3 phone.py Name:CecilPhone number(p) or address(a)?aCecil‘s address is Baz avenue 90.[[email protected] dict]# # 查询的参数错误的情况下[[email protected] dict]# python3 phone.py Name:PengPhone number(p) or address(a)?bYour Input Options Error.
"Python Basics" make a small query database with a dictionary