如何在Python中创建以函数为选项的菜单?字典操作菜单实现求助
Hey there! Let’s get your dictionary tool wrapped into a smooth, interactive menu system—this is a super common pattern in Python scripts, so I’ll walk you through a complete, working example that fixes your function calling issues and shows you how to build this kind of menu properly.
First, I’ve encapsulated all your dictionary operations into standalone functions, then built a looping menu that uses a function-mapping dictionary to keep the selection logic clean and maintainable. Here’s the full code:
def create_dict(): user_dict = {} num_entries = int(input("请输入要添加的键值对数量: ")) for _ in range(num_entries): key = input("请输入键: ") value = input("请输入值: ") user_dict[key] = value print("字典创建完成!") return user_dict def update_dict(user_dict): if not user_dict: print("请先创建一个字典!") return key = input("请输入要更新的键: ") if key in user_dict: new_value = input("请输入新的值: ") user_dict[key] = new_value print(f"键 {key} 的值已更新为 {new_value}") else: print("该键不存在于字典中!") def sort_dict_by_key(user_dict): if not user_dict: print("请先创建一个字典!") return sorted_dict = dict(sorted(user_dict.items())) print("按键排序后的字典:") for k, v in sorted_dict.items(): print(f"{k}: {v}") def sort_dict_by_value(user_dict): if not user_dict: print("请先创建一个字典!") return # 按值排序,若值类型多样可根据需求调整比较逻辑 sorted_dict = dict(sorted(user_dict.items(), key=lambda item: item[1])) print("按值排序后的字典:") for k, v in sorted_dict.items(): print(f"{k}: {v}") def check_exists(user_dict): if not user_dict: print("请先创建一个字典!") return target = input("请输入要查找的键或值: ") if target in user_dict: print(f"键 '{target}' 存在于字典中,对应的值是 {user_dict[target]}") elif target in user_dict.values(): matching_keys = [k for k, v in user_dict.items() if v == target] print(f"值 '{target}' 存在于字典中,对应的键有: {matching_keys}") else: print("该元素不存在于字典中!") def count_unique_values(user_dict): if not user_dict: print("请先创建一个字典!") return unique_values = len(set(user_dict.values())) print(f"字典中唯一值的数量是: {unique_values}") def save_dict_to_file(user_dict): if not user_dict: print("请先创建一个字典!") return filename = input("请输入要保存的文件名(例如: my_dict.txt): ") with open(filename, 'w', encoding='utf-8') as f: for k, v in user_dict.items(): f.write(f"{k}: {v}\n") print(f"字典已成功保存到 {filename}") def main_menu(): user_dict = {} while True: print("\n===== 字典操作菜单 =====") print("1. 创建新字典") print("2. 更新字典") print("3. 按键排序字典") print("4. 按值排序字典") print("5. 查找元素是否存在") print("6. 统计唯一值数量") print("7. 保存字典到文件") print("8. 退出程序") try: choice = int(input("\n请输入你的选择(1-8): ")) except ValueError: print("无效输入!请输入一个数字(1-8)。") continue # 用字典映射选项到对应函数,简洁易扩展 menu_actions = { 1: lambda: create_dict(), 2: lambda: update_dict(user_dict), 3: lambda: sort_dict_by_key(user_dict), 4: lambda: sort_dict_by_value(user_dict), 5: lambda: check_exists(user_dict), 6: lambda: count_unique_values(user_dict), 7: lambda: save_dict_to_file(user_dict), 8: exit } if choice in menu_actions: # 单独处理创建字典的情况,更新全局维护的user_dict if choice == 1: user_dict = menu_actions[choice]() else: menu_actions[choice]() else: print("无效选择!请输入1-8之间的数字。") if __name__ == "__main__": main_menu()
Key Details to Fix Your Issues:
- Modular Functions: Each dictionary operation is its own function, making it easy to call from the menu and debug individually.
- Input Validation: The
try-exceptblock catches non-numeric input, preventing the program from crashing when users enter something unexpected. - Function Mapping: The
menu_actionsdictionary links menu numbers directly to functions—this is way cleaner than a long chain ofif-elifstatements, and adding new features only requires adding a new key-value pair to the dictionary. - State Management: The
user_dictvariable is maintained in the main menu loop, so all operations work on the same dictionary instance (no lost data between menu selections!).
This setup should resolve any function calling problems you were facing—run the script, and you’ll have a fully interactive menu for all your dictionary tasks.
内容的提问来源于stack exchange,提问作者Weller

