如何通过用户输入访问特定词典?

2024-04-25 22:02:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了两个字典dict1dict2。我希望用户通过输入告诉我要访问哪个词典(当然他必须知道确切的名称),这样他就可以从这个词典中得到一个值。下面的不可行,我得到一个

Type Error "string indices must be integers":

dict1 = {'size': 38.24, 'rate': 465}
dict2 = {'size': 32.9, 'rate': 459}

name = input('Which dictionary to access?: ')
ret = name['size']
print ('Size of ' + name + ' is ' + str(ret))

Tags: 用户name名称sizestring字典定义rate
2条回答
dict1 = {'size': 38.24, 'rate': 465}
dict2 = {'size': 32.9, 'rate': 459}

name = input('Which dictionary to access?: ')

if name == 'dict1':
  ret = dict1['size']
eif name == 'dict2':
  ret = dict2['size']


print ('Size of ' + name + ' is ' + str(ret))

或者

   input_to_dict_mapping = {'dict1':dict1,'dict2':dict2}
   ret = input_to_dict_mapping[name]['size']

或者是安特万的反应。你知道吗

已更新

input_to_dict_mapping = globe()
ret = input_to_dict_mapping[name]['size']

问题是name is a string value。你不能像我们在Dict中那样做索引

globals()返回包含已定义的所有全局变量的dict:

>>> globals()
{'dict1': {'rate': 465, 'size': 38.24}, 'dict2': {'rate': 459, 'size': 32.9}, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:/Users/xxx/.PyCharm2018.3/config/scratches/scratch.py', '__package__': None, '__name__': '__main__', '__doc__': None}

所以您应该能够使用globals()[name]检索正确的变量。但请记住,这是一种可怕的方法:变量名不是动态的。您应该使用全局dict来执行这种处理:

dicts = {
    "dict1": {'size': 38.24, 'rate': 465},
    "dict2": {'size': 32.9, 'rate': 459},
}

name = input('Which dictionary to access?: ')
ret = dicts[name]

print ('Size of ' + name + ' is ' + str(ret))

相关问题 更多 >