You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用变量值作为嵌套字典键名失败,该需求是否可实现?

Creating a nested dictionary with keys from variable values

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 of person1), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:13:59