如何将用户输入作为变量名,并为其分配字典、列表等数据结构?
Great question! Let’s break down how to assign dictionaries (or other data structures like lists and sets) to a variable name that a user inputs directly in Python. The key thing to know is: you can’t directly write input("Insert Exercise Name: ") = { ... } because the left side of an assignment needs to be a valid variable name (an identifier). Instead, we can use Python’s namespace tools or a dedicated container to make this happen.
Assigning to User-Defined Variable Names
For Dictionaries
Here’s how you can make your exercise dictionary example work using the global namespace (globals()):
# Define your exercise data first exercise_details = {"sets": 3, "reps": 12, "weight": 100} # Get the desired variable name from the user exercise_name = input("Insert Exercise Name: ") # Assign the dictionary to that variable name in the global scope globals()[exercise_name] = exercise_details # Test it out: if the user entered "bench_press", you can now use that variable print(bench_press) # Output: {'sets': 3, 'reps': 12, 'weight': 100}
For Lists
The exact same logic applies to lists. Let’s say you want to assign a list of workout tips to a user-named variable:
tip_list = ["Warm up for 5 minutes", "Keep core tight"] var_name = input("Enter a name for your tip list: ") globals()[var_name] = tip_list # If the user entered "squat_tips", this will work print(squat_tips) # Output: ['Warm up for 5 minutes', 'Keep core tight']
For Sets
No changes needed for sets either—just swap out the data structure:
required_equipment = {"dumbbells", "mat", "resistance band"} var_name = input("Enter a name for your equipment set: ") globals()[var_name] = required_equipment # If the user entered "yoga_gear", check the output print(yoga_gear) # Output: {'dumbbells', 'mat', 'resistance band'}
A Safer, More Organized Alternative
Using globals() can clutter your code’s namespace and risk overwriting existing variables accidentally. A better practice is to store all your user-named data in a dedicated dictionary. This keeps everything organized and avoids unexpected issues:
# Create a container to hold all your workout data workout_log = {} # Get the exercise name and assign the data to the container exercise_name = input("Insert Exercise Name: ") workout_log[exercise_name] = {"sets": 3, "reps": 12, "weight": 100} # Access the data later using the container print(workout_log[exercise_name]) # Output: {'sets': 3, 'reps': 12, 'weight': 100} # Or if you know the exact name the user entered print(workout_log["bench_press"])
内容的提问来源于stack exchange,提问作者Antônio Gonçalves

