如何让Python的input默认返回变量而非字符串?
解决从字符串获取对应字典对象的问题
方法一:用映射字典(推荐,安全可控)
这是最稳妥的方式,手动建立输入字符串和字典对象的对应关系,完全可控,还能处理输入错误的情况:
dict1 = {'Joe':'three', 'Bob':'nine'} dict2 = {'Jill':'apple', 'Karen':'blanket'} # 建立字符串到字典的映射 dict_mapping = {'dict1': dict1, 'dict2': dict2} user_input = input('Type in the dict you would like to access: ') # 通过get方法获取字典,不存在时返回None target_dict = dict_mapping.get(user_input) if target_dict: # 这里可以正常用target_dict[key]操作字典 print(target_dict['Joe'] if user_input == 'dict1' else target_dict['Jill']) else: print('输入的字典名称不存在,请输入dict1或dict2')
方法二:用globals()(简单但有风险)
globals()会返回当前全局作用域的所有变量字典,可通过输入的字符串键直接取到对应的对象:
dict1 = {'Joe':'three', 'Bob':'nine'} dict2 = {'Jill':'apple', 'Karen':'blanket'} user_input = input('Type in the dict you would like to access: ') target_dict = globals().get(user_input) # 额外判断是不是字典,避免取到其他类型的变量 if target_dict and isinstance(target_dict, dict): print(target_dict['Bob']) else: print('请输入有效的字典名称')
注意:如果用户输入了其他全局变量名(比如print这种内置函数),会拿到非字典对象,甚至触发意外操作,只适合自己测试用,别在公开程序里使用。
方法三:用eval()(强烈不推荐)
eval()可以直接执行字符串代码,虽然能实现需求,但风险极大——如果用户输入恶意代码,会直接执行(比如删除文件、窃取数据等):
dict1 = {'Joe':'three', 'Bob':'nine'} dict2 = {'Jill':'apple', 'Karen':'blanket'} user_input = input('Type in the dict you would like to access: ') try: target_dict = eval(user_input) if isinstance(target_dict, dict): print(target_dict['Karen']) else: print('输入的不是字典') except: print('输入无效')
警告:绝对不要在有不可信用户输入的场景使用eval!
内容的提问来源于stack exchange,提问作者hiiiiii
相关产品推荐
相关产品推荐

