一对多转多对一:字典列表映射转换及实现问题咨询
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
- Use a temporary dictionary to accumulate subIds for each mainId—this helps us group all subIds that map to the same mainId.
- Iterate through each entry in your original list, extracting the subId and its associated mainIds.
- For each mainId, add the subId to its corresponding list in the temporary dictionary (initialize the list if the mainId isn't already present).
- 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
相关产品推荐
相关产品推荐

