如何访问嵌套字典中所有顶级键下的同一子键?
Hey there! No worries about spelling mistakes at all—we all start out as newbies, and asking questions is the best way to grow your coding skills. 😊
First off, let's be clear: In Python, there's no way to completely skip iterating through each person to access all the city or age values directly. Each person_x is a separate key-value pair in your top-level dictionary, and their inner dictionaries are stored independently. That said, we can use some clean, Pythonic shortcuts that feel like "one-step" operations, and they're just as efficient (if not more) than writing a full manual loop.
1. 对所有年龄求和
The most efficient and readable way to sum all age values is using a generator expression with Python's built-in sum() function:
# 先定义你的字典(补全了city的值示例) people_dict = { "person_1": {"city": "Paris", "age": 18}, "person_2": {"city": "Sydney", "age": 25}, "person_3": {"city": "Berlin", "age": 57} } # 计算总年龄 total_age = sum(person["age"] for person in people_dict.values()) print(total_age) # 输出: 100
这里people_dict.values() gives us all the inner dictionaries (each person's data), and the generator expression pulls out the age from each one. Generators are memory-efficient because they don't create a full list of ages first—they feed values directly to sum().
2. 获取所有城市的列表
If you want to collect all city values into a list, use a list comprehension:
all_cities = [person["city"] for person in people_dict.values()] print(all_cities) # 输出: ['Paris', 'Sydney', 'Berlin']
3. 处理可能缺失的键
If some entries might not have an age or city (to avoid KeyError), add a quick check:
# 只对有age键的条目求和 safe_total_age = sum(person["age"] for person in people_dict.values() if "age" in person) # 只收集有city键的城市 safe_cities = [person["city"] for person in people_dict.values() if "city" in person]
为什么这些方法是最优的?
Even though these approaches technically iterate through each person, they're optimized by Python's internals—they run just as fast (or faster) than writing a manual for loop with an accumulator variable. Plus, they're concise and easy to read, which makes your code cleaner for future you (or other developers) to understand.
So don't stress about "avoiding loops"—the structure of nested dictionaries means we have to access each entry, but these shortcuts make the process feel seamless.
内容的提问来源于stack exchange,提问作者Eduardo Vinnícius

