使用变量值作为嵌套字典键名失败,该需求是否可实现?
Hey there! Let's break this down for you—yes, using variable values as keys for nested dictionaries is totally feasible in Python—so the issue is almost certainly a small detail in your implementation. Let's walk through examples, common pitfalls, and fixes.
First, let's assume your expected outcome looks something like this (a common scenario):
# Expected result example people = { "Alice": {"age": 30, "city": "New York"}, "Bob": {"age": 25, "city": "London"} }
Working Implementations
Here are two common ways to pull this off correctly:
1. Static Nested Dictionary (Direct Variable Use)
If you're defining the dictionary explicitly with variables:
# Define your key variables person1 = "Alice" person2 = "Bob" age_key = "age" city_key = "city" # Build the nested dictionary people = { person1: { age_key: 30, city_key: "New York" }, person2: { age_key: 25, city_key: "London" } } print(people) # Output: {'Alice': {'age': 30, 'city': 'New York'}, 'Bob': {'age': 25, 'city': 'London'}}
2. Dynamic Generation (Loop-Based)
If you need to create multiple nested entries programmatically (like from a list of names):
# List of variable values to use as top-level keys user_names = ["Alice", "Bob", "Charlie"] # Keys for the inner dictionaries inner_keys = ["age", "city"] # Initialize empty nested dictionary nested_people = {} for name in user_names: # Create an inner dict for each user nested_people[name] = {key: "" for key in inner_keys} # Populate with custom values nested_people[name]["age"] = 25 + user_names.index(name) nested_people[name]["city"] = ["New York", "London", "Paris"][user_names.index(name)] print(nested_people) # Output: # { # 'Alice': {'age': 25, 'city': 'New York'}, # 'Bob': {'age': 26, 'city': 'London'}, # 'Charlie': {'age': 27, 'city': 'Paris'} # }
Common Mistakes to Check
If your code isn't working, here are the most likely culprits:
- Undefined Variables: If you reference a variable that hasn't been declared, you'll get a
NameError. Double-check that all variables used as keys exist. - Unhashable Key Types: Dictionary keys must be hashable (strings, numbers, tuples work—lists, dictionaries, and other mutable types don't). If you're trying to use a list as a key, you'll hit a
TypeError. - Accidental String Literals: It's easy to accidentally wrap a variable in quotes (e.g., writing
"person1"instead ofperson1), which uses the string "person1" as the key instead of the variable's value. - Syntax Errors: If you're using older Python versions (pre-3.5), some dictionary comprehension syntax might not work—but this is rare these days.
Example of a common error:
# ❌ Error: Undefined variable bad_dict = { undefined_name: {"age": 30} } # Throws NameError: name 'undefined_name' is not defined # ❌ Error: Unhashable key (list) invalid_key = ["Alice"] bad_dict = { invalid_key: {"age": 30} } # Throws TypeError: unhashable type: 'list'
Final Verdict
To answer your core question: Yes, this approach is absolutely feasible. The problem is almost certainly a small oversight in your code. Go through the checks above, and you'll get it working in no time!
内容的提问来源于stack exchange,提问作者EthanB

