1
bob = {'age' : 26 , 'fullname' : 'Bob Dwayne Lee' , 'status' : 'married'}
name = input('whats your name? ') #user input is bob
print (name['age'])

TypeError: string indices must be integers

sabloxine
  • 11
  • 1
  • 1
    I think I found a perfect match for this. Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Alexander May 03 '22 at 17:58
  • 1
    The question doesn't match your example. You aren't showing an attempt to use a variable as a dictionary *key*, but an attempt to use a string variable as if it were a dictionary. – jjramsey May 03 '22 at 17:59
  • Where the code says `name['age']`, what do you expect that to mean? Your question asks "how do I use a variable as a dictionary key?", so I assume that is what you are trying to do in the erroneous line. Think more carefully about what you are trying to do. What variable do you want to use as the key, and what dictionary do you want to use it in? Therefore, how should the code read? – Karl Knechtel May 03 '22 at 18:14
  • It seems like you want to use the text `'bob'` as a key, from the user's input (which will be named with the variable `name`). To look up this key in a dictionary, you would have to have a dictionary *where that is one of the keys*. Think more carefully about how to structure the data. (Hint: it is perfectly permissible to nest dictionaries, just as one would nest lists.) – Karl Knechtel May 03 '22 at 18:16

1 Answers1

1

You wouldn't.

Instead, you would make a variable that stores all your record by their own key, and lookup into that:

all_users = {
  'bob': { 'age': 26 , 'fullname': 'Bob Dwayne Lee' , 'status': 'married'}
}
name = input('whats your name? ') #user input is bob
print(all_users[name]['age'])
Alexander
  • 59,041
  • 12
  • 98
  • 151