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

一对多转多对一:字典列表映射转换及实现问题咨询

Solution to Convert the Dictionary List

First, let's fix the code to group subIds under each mainId correctly. The issue with your original code is that it creates a separate entry for every mainId-subId pair instead of grouping them together. Here's how to adjust it:

Step-by-Step Code Explanation

  1. Use a temporary dictionary to accumulate subIds for each mainId—this helps us group all subIds that map to the same mainId.
  2. Iterate through each entry in your original list, extracting the subId and its associated mainIds.
  3. For each mainId, add the subId to its corresponding list in the temporary dictionary (initialize the list if the mainId isn't already present).
  4. Finally, convert the temporary dictionary into your desired list format.

Working Python Code

list1 = [
    {'subId': 0, 'mainIds': [0]},
    {'subId': 3, 'mainIds': [0, 3, 4, 5], 'parameter': 'off', 'Info': 'true'}
]

# Temporary dict to group subIds by mainId
main_to_subs = {}

for item in list1:
    sub_id = item['subId']
    for main_id in item['mainIds']:
        # Initialize empty list if mainId isn't in the dict yet
        if main_id not in main_to_subs:
            main_to_subs[main_id] = []
        # Add the current subId to the mainId's list
        main_to_subs[main_id].append(sub_id)

# Convert the dict to the target list structure
final_res = [{'mainId': mid, 'subIds': sids} for mid, sids in main_to_subs.items()]

print(final_res)

Output

[{'mainId': 0, 'subIds': [0, 3]}, {'mainId': 3, 'subIds': [3]}, {'mainId': 4, 'subIds': [3]}, {'mainId': 5, 'subIds': [3]}]

What's This Operation Called?

This is commonly referred to as inverting a one-to-many mapping or grouping by the target of a one-to-many relationship. You’re taking multiple entries where each subId maps to several mainIds, and reversing that logic to group all subIds that map to each individual mainId. It’s a core aggregation/grouping task in data processing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 15:22:27