Python无法提取字典值存入列表实现生日排序的问题
问题原因
你当前的birth_dict中,每个值都是嵌套的小字典(比如{"张三": "01 Jan 2000"}),所以调用values()返回的是这些小字典的视图对象,而不是你需要的生日字符串或姓名+生日的组合,这就是为什么你拿到的还是类似字典的内容。
解决方法
首先调整数据存储结构,不用嵌套字典,直接把姓名作为键、生日字符串作为值存在birth_dict里(或者用列表存储(姓名, 生日)元组,更灵活),之后就能轻松提取需要的数据并排序。
修改后的代码
from datetime import datetime birth_dict = {} def date_key(item): # 适配字典items()返回的(姓名, 生日字符串)元组,取第二个元素转datetime return datetime.strptime(item[1], "%d %b %Y") while True: name = input("Enter name of person: ") birth_month = input("What month were they born?: ") birth_day = input("What day of the month were they born?: ") birth_year = input("what year were they born?: ") birth_day = str(birth_day) if len(birth_day) == 1: birth_day = "0" + birth_day birth_month = birth_month[:3].capitalize() birthdate = f"{birth_day} {birth_month} {birth_year}" # 直接用姓名作为键存储生日,避免嵌套字典 birth_dict[name] = birthdate new_date = input("Do you want to enter another birthday?\n\nY for yes N for no\n\n") if new_date.lower() != "y": break # 提取字典的键值对,按生日排序 sorted_birthdays = sorted(birth_dict.items(), key=date_key) # 打印排序后的结果 print("按生日排序的结果:") for name, bday in sorted_birthdays: print(f"{name}: {bday}")
关键调整说明
- 去掉了多余的
dict_place计数器,直接用姓名作为字典的键,结构更清晰 - 修改
date_key函数,适配字典items()返回的(姓名, 生日)元组 - 使用
sorted()函数结合date_key,直接完成按生日的排序 - 如果需要支持重名或保留输入顺序,可以改用列表存储元组:
birth_list = [] # 存储时改为 birth_list.append( (name, birthdate) ) # 排序时 sorted_birthdays = sorted(birth_list, key=lambda x: datetime.strptime(x[1], "%d %b %Y"))
内容的提问来源于stack exchange,提问作者Zachary Hargett
相关产品推荐
相关产品推荐

