0

I have defined two dictionaries dict1 and dict2. I want the user to tell me via input, which dictionary to access (of course he has to know the exact names), so he gets a value from this dictionary. The following doesn't work out, I get a

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))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
h_s
  • 9
  • 1

2 Answers2

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

or

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

or from Antwane response.

Updated

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

The problem is that name is a string value. you can not do the index as we do it in Dict.

backtrack
  • 7,996
  • 5
  • 52
  • 99
  • But is there a possibility to turn that string into something that I can use, to access the dictionary? – h_s Dec 11 '18 at 09:26
  • yes and see the updated section. as Antwane pointed, You can use globe and get the dict and use it as mentioned in updated section – backtrack Dec 11 '18 at 09:42
0

globals() return a dict containing all global variables already defined:

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

So you should be able to retrieve the right variable using globals()[name]. But keep in mind this is a terrible way to do: variable names aren't meant to be dynamic. You should use a global dict to perform this kind of processing:

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))
Antwane
  • 20,760
  • 7
  • 51
  • 84