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 correspondinginner_dict(like {'1':4,'2':6}), we calculate the value fornewd. max()with a Key Function: Themax()function normally compares the keys themselves, but we use thekeyparameter to tell it to compare the values of those keys instead. The lambda functionlambda k: inner_dict[k]takes each subkey (like '1' or '2') and returns its value (4 or 6), somax()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
相关产品推荐
相关产品推荐

