How to keep an input to represent a variable instead of a str by default
Question:
I’m a beginner in python, and I’m trying to make a program that can refer to a single dictionary out of a couple of dictionaries, and then access its contents. Like this:
dict1 = {'Joe':'three', 'Bob':'nine'}
dict2 = {'Jill':'apple', 'Karen':'blanket'}
a = input('Type in the dict you would like to access: ')
and then hopefully a could == dict1 or dict2, and then I could continue with the rest of my operations
I wanted ‘a’ to be == to dict1 if that’s what the user inputs, so I could later search a like (a[key]), and do other operations with it.
However, it defaults to str, and I don’t know how to get the input to assign the dictionary dict1 to variable a instead of the string ‘dict1’. Any help would be greatly appreciated!
Answers:
With the use of nested dictionaries.
dicts = {
"dict1":{'Joe':'three', 'Bob':'nine'},
"dict2":{'Jill':'apple', 'Karen':'blanket'},
}
a = input('Type in the dict you would like to access: ')
chosen_dict = dicts.get(a)
print(chosen_dict)
I’m a beginner in python, and I’m trying to make a program that can refer to a single dictionary out of a couple of dictionaries, and then access its contents. Like this:
dict1 = {'Joe':'three', 'Bob':'nine'}
dict2 = {'Jill':'apple', 'Karen':'blanket'}
a = input('Type in the dict you would like to access: ')
and then hopefully a could == dict1 or dict2, and then I could continue with the rest of my operations
I wanted ‘a’ to be == to dict1 if that’s what the user inputs, so I could later search a like (a[key]), and do other operations with it.
However, it defaults to str, and I don’t know how to get the input to assign the dictionary dict1 to variable a instead of the string ‘dict1’. Any help would be greatly appreciated!
With the use of nested dictionaries.
dicts = {
"dict1":{'Joe':'three', 'Bob':'nine'},
"dict2":{'Jill':'apple', 'Karen':'blanket'},
}
a = input('Type in the dict you would like to access: ')
chosen_dict = dicts.get(a)
print(chosen_dict)