八年级上册¶

第一单元 用计算机程序解决问题¶

第2节 神奇的字典¶

一、认识字典¶

In [2]:
d1 = {}
d2 = dict()
d3 = {'张三':13000000000, '李四':13700000000}
d4 = {13000000000:'张三', 13700000000:'李四'}
print(d3)
print(d4)
{'张三': 13000000000, '李四': 13700000000}
{13000000000: '张三', 13700000000: '李四'}

二、字典的基本操作¶

In [3]:
# 1.添加或修改 键-值
d1 = {}
d1[1] = '张三'
print(d1)
d1[1] = '李四'
print(d1)
{1: '张三'}
{1: '李四'}
In [26]:
# 2.查询键所对应的值
d3 = {'张三':13000000000, '李四':13700000000}
print(d3['张三'])
print(d3.get('张三'))
13000000000
13000000000
In [28]:
d4 = {13000000000:'张三', 13700000000:'李四'}
print(d4[13100000000])  # 会出错,下一句无法运行,若要让下一句运行,请用#注释掉本语句
print(d4.get(13100000000))  # 不存在,输出None
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In [28], line 2
      1 d4 = {13000000000:'张三', 13700000000:'李四'}
----> 2 print(d4[13100000000])  # 会出错
      3 print(d4.get(13100000000))

KeyError: 13100000000
In [11]:
d4 = {13000000000:'张三', 13700000000:'李四'}
print(d4.get(13100000000, '不存在'))  # 不存在,输出默认值
不存在
In [12]:
# 3.删除键-值对
d4 = {'13000000000':'张三', '13700000000':'李四'}  # 注意此处键为字符串,与上文不同
del d4['13000000000']
print(d4)
{'13700000000': '李四'}
In [14]:
# 4. 取字典的集
d3 = {'张三':13000000000, '李四':13700000000}
a = d3.keys()
b = d3.values()
c = d3.items()
print(a, b, c, sep='\n')
for name, tele in c:
    print(name, tele)
dict_keys(['张三', '李四'])
dict_values([13000000000, 13700000000])
dict_items([('张三', 13000000000), ('李四', 13700000000)])
张三 13000000000
李四 13700000000

实践活动:设计简易通讯录系统¶

In [16]:
# 简易通读录系统
# 建议在受邀人员管理程序的基础上进行设计
menu = '''               简易通讯录\n
请选择(1.查询 2.增加 3.删除 4.修改 5.退出系统):'''
d = {'张三':13000000000, '李四':13700000000}
while True:
    c = int(input(menu))
    if c == 1:  # 查询
        print('姓  名  手机号')
        for name, tele in d.items():
            print('{}  =>  {}'.format(name, tele))
    elif c == 2:  # 增加
        name, tele = input('请输入姓名和手机号,用空格分开:').split()
        d[name] = int(tele)
        print('{}:{} 已增加。'.format(name, tele))
    elif c == 3:  # 删除
        name = input('请输入要删除的人员姓名:')
        del d[name]
        print('{}已删除'.format(name))
    elif c == 4: # 修改
        name = input('请输入要修改的姓名:')
        tele = input('你要把{}的手机号改为:'.format(name))
        d[name] = int(tele)
        print('{}的手机号已修改完成!'.format(name))        
    elif c == 5:  # 退出
        break
    
print('再见!')
               简易通讯录

请选择(1.查询 2.增加 3.删除 4.修改 5.退出系统):5
再见!

三、字典的应用¶

In [20]:
# 1.用字典优化多分支结构
import random
choice = ['','石头','剪子','布']
result = {0:'平局', -1:'你赢', 1:'你输', 2:'你赢', -2:'你输'}
user = int(input('请你出(1.石头;2.剪子;3.布):'))
print('你出:{}。'.format(choice[user]))
computer = random.randint(1, 3)
print('计算出:{}。'.format(choice[computer]))
print(result[user - computer])
请你出(1.石头;2.剪子;3.布):3
你出:布。
计算出:石头。
你赢
In [8]:
# 简易通读录系统 改编版
# 建议在受邀人员管理程序的基础上进行设计
import sys

def f1():
    '''查询'''
    print('姓  名  手机号')
    for name, tele in d.items():
        print('{}  =>  {}'.format(name, tele))    


def f2():
    '''增加'''
    name, tele = input('请输入姓名和手机号,用空格分开:').split()
    d[name] = int(tele)
    print('{}:{} 已增加。'.format(name, tele))    
 

def f3():
    '''删除'''
    name = input('请输入要删除的人员姓名:')
    del d[name]
    print('{}已删除'.format(name))   

def f4():
    '''修改'''
    name = input('请输入要修改的姓名:')
    tele = input('你要把{}的手机号改为:'.format(name))
    d[name] = int(tele)
    print('{}的手机号已修改完成!'.format(name))

def f5():
    '''退出'''
    global Flag
    Flag = False
    print('再见!')


menu = {1:f1, 2:f2, 3:f3, 4:f4, 5:f5}
title = '''               简易通讯录\n
请选择(1.查询 2.增加 3.删除 4.修改 5.退出系统):'''
d = {'张三':13000000000, '李四':13700000000}
Flag = True  # 退出循环标志
while Flag:  # 这里采用Flag标志
    sel = int(input(title))
    menu[sel]()
               简易通讯录

请选择(1.查询 2.增加 3.删除 4.修改 5.退出系统):5
再见!
In [9]:
# 2.字典类型与JSON数据类型相互转化
import json
a = '{"姓名":"小林","年龄":12}'
b = json.loads(a)
print(b)
c = json.dumps(b, ensure_ascii=False)
print(c)
{'姓名': '小林', '年龄': 12}
{"姓名": "小林", "年龄": 12}
In [1]:
# %%writefile tianqi.py
# 提供天气实况服务的模拟服务器
# 需安装flask: pip install flask
# 需把本单元格内容用 %%writefile tq.py 命令保存至tianqi.py,并在终端用python tq.py来运行,出现以下提示:
# WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
# * Running on all addresses (0.0.0.0)
# * Running on http://127.0.0.1:5000
#  * Running on http://192.168.1.104:5000
# Press CTRL+C to quit
# 表明服务器正常,把 http://192.168.1.104:5000 网址提供给学生即可。

from flask import Flask
import requests
import os
import time
import pickle
import json


def getWeather():
    '''天气数据api,返回json文本数据'''
    if os.path.exists('tianqi.bin'):
        print('正在从tianqi.bin中读取变量...')
        with open('tianqi.bin', 'rb') as f:
            txt = pickle.load(f) #读取变量值
            dic = json.loads(txt)
            address = dic["fxLink"]
            update = dic["updateTime"]
            a = list(map(int,update.split('T')[0].split('-')))
            b = [time.localtime().tm_year,time.localtime().tm_mon,time.localtime().tm_mday]
            if a==b:
                print('利用已存在数据{}.'.format(a))
                return txt
    print('将tianqi.bin数据更新到{}.'.format([time.localtime().tm_year,time.localtime().tm_mon,time.localtime().tm_mday]))
    key = '4eba8e5f50f04858ba132c2c7c06edda' # 只是演示的免费订阅key,务必替换为您自己的和风天的key, 注册地址:https://id.qweather.com/#/login
    loc = '101150101' # 设置地区码(此处为西宁),可以到网页https://www.qweather.com/weather/xining-101150101.html查找,
                      #.html前的这串数字。https://www.qweather.com/weather/xining-101150101.html
    url = 'https://devapi.qweather.com/v7/weather/now?location={}&key={}'.format(loc, key)  # 这里采用和风天气免费订阅
    #提供动态内容,否则注释之
    txt = requests.get(url).content.decode()
    # 如果以上三行程序不能正常运行,请采用下面固定的格式来提供
    # 若提供固定内容,则修改下面的内容,且下行txt去掉注释(默认),此处数据格式是从和风实时天气服务api(感谢和风天气的免费订阅服务)
    #txt=\
    '''{
    "code":"200",
    "updateTime":"2023-08-19T21:22+08:00",
    "fxLink":"https://www.qweather.com/weather/xining-101150101.html",
    "now":{
        "obsTime":"2023-08-19T21:14+08:00",
        "temp":"16",
        "feelsLike":"14",
        "icon":"150",
        "text":"晴",
        "wind360":"135",
        "windDir":"东南风",
        "windScale":"2",
        "windSpeed":"7",
        "humidity":"48",
        "precip":"0.0",
        "pressure":"762",
        "vis":"30",
        "cloud":"10",
        "dew":"10"
    },
    "refer":{
        "sources":[
            "QWeather",
            "NMC",
            "ECMWF"
        ],
        "license":[
            "CC BY-SA 4.0"
        ]
    }
}'''
    with open('tianqi.bin', 'wb') as f:
        pickle.dump(txt, f) #把a存入文件中
    return txt


app = Flask(__name__)
app.debug = True
@app.route('/')
def hello_world():
    return getWeather()

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000)
Writing tianqi.py
In [ ]:
# 技术支持
import requests
import json

# 要访问的API网址(这里参数可参考相应API开发者文档)
# 教师可以运行tianqi.py来搭建本地天气数据服务器,把地址告诉学生作为api网址
url = '具体api网址'
# 通过requests获取内容并解码后赋值给txt,这个过程可能需一点时间等待
txt = requests.get(url).content.decode()
# json格式字符串转化为字典类型
dic = json.loads(txt)
print(dic)

#获取的天气api参考格式,具体因天气服务api不同而不同,请参考相应api文档或老师告知的格式。
    #txt=\
    '''{
    "code":"200",
    "updateTime":"2023-08-19T21:22+08:00",
    "fxLink":"https://www.qweather.com/weather/xining-101150101.html",
    "now":{
        "obsTime":"2023-08-19T21:14+08:00",
        "temp":"16",
        "feelsLike":"14",
        "icon":"150",
        "text":"晴",
        "wind360":"135",
        "windDir":"东南风",
        "windScale":"2",
        "windSpeed":"7",
        "humidity":"48",
        "precip":"0.0",
        "pressure":"762",
        "vis":"30",
        "cloud":"10",
        "dew":"10"
    },
    "refer":{
        "sources":[
            "QWeather",
            "NMC",
            "ECMWF"
        ],
        "license":[
            "CC BY-SA 4.0"
        ]
    }
}'''
In [25]:
# 学生参考程序
import requests
import json
url = 'http://192.168.1.104:5000'  # 这是连接天气数据的模拟服务器,由教师提供
try:
    txt = requests.get(url).content.decode()
    # print(txt)
    dic = json.loads(txt)
    # print(dic)
    nowDic = dic['now']
    text = nowDic['text']  # 天气
    temp = nowDic['temp']  # 气温
    windDir = nowDic['windDir']  # 风向
    windScale = nowDic['windScale'] # 风级
    html = dic['fxLink']  # 网址
    print('最新天气播报:{},气温{}摄氏度,{}{}级。\n详情请关注{}。'.format(text, temp, windDir, windScale, html))
except:
    print('对不起,天气服务器无法接通。')
最新天气播报:晴,气温15摄氏度,东南风1级。
详情请关注https://www.qweather.com/weather/xining-101150101.html。
In [ ]:
import os
os.system('python tianqi.py')
In [5]:
import sys
No Python documentation found for 'D:\\XEdu\\envs\\interpreter\\python.exe'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

In [ ]: