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

Python新手求助:如何在嵌套字典中获取各外层键对应最高值的子键

Optimal Solution for Your Dictionary Problem

Hey there! As a Python newbie, this is a great problem to learn about dictionary comprehensions and the max() function—two super useful tools in your Python toolkit.

The most concise and efficient way to get your desired newd is with a dictionary comprehension combined with max() using a custom key. Here's the one-liner that does exactly what you need:

d = {'a':{'1':4,'2':6},'b':{'1':5,'2':10}}
newd = {outer_key: max(inner_dict, key=lambda k: inner_dict[k]) for outer_key, inner_dict in d.items()}
print(newd)  # Output: {'a': '2', 'b': '2'}

Let's break this down step by step:

  • Dictionary Comprehension: This is a shorthand way to build a new dictionary by iterating over the original one. For each outer_key (like 'a' or 'b') and its corresponding inner_dict (like {'1':4,'2':6}), we calculate the value for newd.
  • max() with a Key Function: The max() function normally compares the keys themselves, but we use the key parameter to tell it to compare the values of those keys instead. The lambda function lambda k: inner_dict[k] takes each subkey (like '1' or '2') and returns its value (4 or 6), so max() picks the subkey with the highest value.

If you prefer a more explicit step-by-step approach (great for learning):

If comprehensions feel a bit overwhelming at first, you can write it out with a loop instead—same logic, just more verbose:

d = {'a':{'1':4,'2':6},'b':{'1':5,'2':10}}
newd = {}
for outer_key, inner_dict in d.items():
    # Find the subkey with the maximum value
    max_subkey = max(inner_dict, key=lambda k: inner_dict[k])
    newd[outer_key] = max_subkey
print(newd)  # Same output: {'a': '2', 'b': '2'}

Why this is optimal:

  • Efficiency: We only iterate through each outer key once, and for each inner dictionary, we check every value exactly once. This is the best possible time complexity (O(n*m) where n is the number of outer keys and m is the number of subkeys) since you can't find the maximum without checking all values.
  • Readability: Once you get comfortable with comprehensions and lambda functions, this code is clean and clearly expresses what you're trying to do.
  • Pythonic: This follows Python's philosophy of writing concise, readable code that gets the job done without unnecessary boilerplate.

内容的提问来源于stack exchange,提问作者CWeeks

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:11:02