Home > Article > Backend Development > Here are a few title options, keeping in mind the question-answer format and the article\'s focus on grouping data pairs in Python: Option 1 (General): * How to Group Data Pairs in Python Based on S
Problem:
Given a set of data pairs, group them based on the value at a specified index and convert them into a desired format.
Solution:
To efficiently group data pairs by their type, follow these steps:
Step 1: Create a Dictionary
Create a dictionary using the defaultdict from the collections module, where the keys are the types and the values are lists of values:
<code class="python">from collections import defaultdict res = defaultdict(list) for v, k in input: res[k].append(v)</code>
Step 2: Convert Dictionary to Desired Format
Convert the created dictionary into a list of dictionaries with the desired format:
<code class="python">result = [{'type': k, 'items': v} for k,v in res.items()]</code>
Additional Considerations:
Alternative Approach Using **itertools.groupby()**:
An alternative approach involves using the itertools.groupby function, but requires the input data to be sorted terlebih dahulu.
<code class="python">import operator as itemgetter import itertools sorted_input = sorted(input, key=itemgetter(1)) groups = itertools.groupby(sorted_input, key=itemgetter(1)) result = [{'type': k, 'items':[x[0] for x in v]} for k, v in groups]</code>
The above is the detailed content of Here are a few title options, keeping in mind the question-answer format and the article\'s focus on grouping data pairs in Python: Option 1 (General): * How to Group Data Pairs in Python Based on S. For more information, please follow other related articles on the PHP Chinese website!