关于《Python Crash Course》第8章字典用户输入示例的疑问
理解字典的键值对存储逻辑
你觉得这段代码只把response存入字典,其实是没搞清楚Python字典的键值对工作方式——字典本身就是通过「唯一的键」关联「对应的值」来存储数据的,这段代码里的姓名和响应正是以这种成对的方式存进去的。
咱们一步步拆解逻辑:
- 首先初始化空字典
responses = {},它的作用就是存储所有投票者的姓名和对应的爬山选择。 - 进入循环后,先获取两个输入:
name = input(...):拿到投票者的姓名,这个会作为字典里的键(key)response = input(...):拿到投票者想爬的山,这个会作为对应键的值(value)
- 关键的一行
responses[name] = response:这行代码的意思是「把name作为键,把response作为这个键对应的值,存入responses字典」。举个例子:- 如果用户输入姓名是"张三",响应是"珠穆朗玛峰",字典就会变成
{"张三": "珠穆朗玛峰"} - 下一个用户输入"李四"和"乔戈里峰",字典就更新为
{"张三": "珠穆朗玛峰", "李四": "乔戈里峰"}
每一轮循环都会新增一组这样的键值对,姓名和响应自然就成对保存了。
- 如果用户输入姓名是"张三",响应是"珠穆朗玛峰",字典就会变成
- 最后遍历
responses.items()时,这个方法会返回字典里的每一组键值对(姓名和对应的响应),所以能把结果一一打印出来。
再看完整代码:
responses = {} # Set a flag to indicate that polling is active. polling_active = True while polling_active: #Prompt for the person's name and response. name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") #Store the response in the dictionary: responses[name] = response #Find out if anyone else is going to take the poll. repeat = input("Would you like to let another person respond? (yes/no) ") if repeat == 'no': polling_active = False #Polling is complete. Show the results. print("\n--- Poll Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")
简单说,字典的每个条目都是「键: 值」的配对,这里姓名是键,响应是值,responses[name] = response就是把这一对数据绑定后存入字典,所以两者是同时被存储的,只是写法上看起来是给键赋值,但本质是新增了一组完整的键值对。
内容的提问来源于stack exchange,提问作者TheRogueDadBot
相关产品推荐
相关产品推荐

