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

Python:对嵌套字典中的元组列表按元组首元素排序

Sort Nested Dictionary Lists by Tuple's First Element

Got it, let's get those nested lists sorted exactly how you want! Here's a couple of Python solutions depending on whether you want to modify your original dictionary or create a sorted copy.

Solution 1: Modify the Original Dictionary In-Place

If you don't need to keep the original unsorted data, you can sort each list directly in-place:

# Your original nested dictionary
original_dict = {
    'AAA': {
        'A1': [(0, ('a', 'b')), (3, ('c', 'd')), (2, ('a', 'b'))],
        'B1': [(3, ('a', 'b')), (2, ('a', 'b')), (1, ('c', 'd'))]
    },
    'BBB': {
        'A1': [(4, ('a', 'b')), (2, ('c', 'd')), (1, ('a', 'b'))],
        'B1': [(3, ('c', 'd')), (2, ('a', 'b')), (1, ('a', 'b'))]
    }
}

# Iterate through each level and sort the lists
for top_level_key in original_dict:
    for sub_key in original_dict[top_level_key]:
        # Sort using the first element of each tuple as the sort key
        original_dict[top_level_key][sub_key].sort(key=lambda item: item[0])

# Verify the sorted result
print(original_dict)

Solution 2: Create a Sorted Copy (Preserve Original Data)

If you need to keep your original dictionary intact, build a new sorted version instead:

original_dict = {
    'AAA': {
        'A1': [(0, ('a', 'b')), (3, ('c', 'd')), (2, ('a', 'b'))],
        'B1': [(3, ('a', 'b')), (2, ('a', 'b')), (1, ('c', 'd'))]
    },
    'BBB': {
        'A1': [(4, ('a', 'b')), (2, ('c', 'd')), (1, ('a', 'b'))],
        'B1': [(3, ('c', 'd')), (2, ('a', 'b')), (1, ('a', 'b'))]
    }
}

sorted_dict = {}
for top_key, sub_dictionary in original_dict.items():
    sorted_sub_dict = {}
    for sub_key, tuple_list in sub_dictionary.items():
        # Use sorted() to generate a new sorted list
        sorted_sub_dict[sub_key] = sorted(tuple_list, key=lambda item: item[0])
    sorted_dict[top_key] = sorted_sub_dict

print(sorted_dict)

How It Works

Both solutions rely on specifying a custom sort key with lambda item: item[0] — this tells Python to use the first element of each tuple as the value to sort by.

  • The sort() method modifies the list directly (in-place), which is efficient if you don't need the original data.
  • The sorted() function returns a brand new sorted list, leaving your original data untouched.

Either approach will give you the exact sorted structure you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:23:25