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

如何在Python中将双元素嵌套列表转为多值有序字典?

Convert Nested List of Dual-Element Sublists to Dictionary in Python

Got it, let's walk through how to solve this problem—turning a nested list where each sublist has exactly two elements into a dictionary, where the first element of each sublist becomes a key, and the second elements are collected into an ordered list for that key.

Method 1: Basic Loop (No External Libraries)

This is the most straightforward approach, perfect if you don't want to rely on any imports. We'll initialize an empty dictionary, then iterate over each sublist, checking if the key already exists. If it does, we append the value to its list; if not, we create a new list with the value.

def nested_list_to_dict(nested_list):
    output_dict = {}
    for key, value in nested_list:
        if key not in output_dict:
            output_dict[key] = []
        output_dict[key].append(value)
    return output_dict

# Test Example 1
example_1 = [['A', 'B'], ['A', 'C'], ['A', 'D']]
print(nested_list_to_dict(example_1))  # Output: {'A': ['B', 'C', 'D']}

# Test Example 2
example_2 = [['A', 'B'], ['A', 'C'], ['A', 'D'], ['B', 'B1'], ['B', 'C1'], ['C', 'B2'], ['C', 'C2'], ['C', 'D2']]
print(nested_list_to_dict(example_2))  # Output: {'A': ['B', 'C', 'D'], 'B': ['B1', 'C1'], 'C': ['B2', 'C2', 'D2']}

Method 2: Use collections.defaultdict (Cleaner Syntax)

If you don't mind importing a standard library module, defaultdict from the collections module simplifies the code by automatically initializing an empty list for new keys. This cuts out the "check if key exists" step entirely.

from collections import defaultdict

def nested_list_to_dict(nested_list):
    output_dict = defaultdict(list)
    for key, value in nested_list:
        output_dict[key].append(value)
    # Convert to a regular dictionary if needed (optional)
    return dict(output_dict)

# Testing with the same examples will give identical results

Key Notes

  • Order Preservation: Both methods keep the order of values exactly as they appear in the original list. In Python 3.7+, regular dictionaries also preserve the order of key insertion, so the keys will appear in the order they first showed up in the input list.
  • Handling Edge Cases: If your input might have sublists that aren't exactly two elements, you can add a quick check to skip or handle them (e.g., if len(item) != 2: continue inside the loop).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:05:52