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

时间:2018-12-11 08:54:25

标签: python dictionary input access

我定义了两个字典dict1dict2。我希望用户通过输入告诉我要访问的词典(当然,他必须知道确切的名称),以便他从该词典中获取一个值。以下内容无法解决,我得到了

  

类型错误“字符串索引必须为整数”:

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))

2 个答案:

答案 0 :(得分:0)

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']

或来自Antwane的回复。

已更新

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

问题是name is a string value。您无法像在Dict中那样做索引。

答案 1 :(得分:0)

globals()返回一个包含所有已定义的全局变量的字典:

>>> 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]来检索正确的变量。但是请记住,这是一种糟糕的方法:变量名并不意味着是动态的。您应该使用全局字典来执行这种处理:

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))