Problem:
Given a set of data pairs where the first item is the value and the second item is the type, group them based on the type.
Example:
input = [ ('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH'), ]
Desired Result:
result = [ { 'type': 'KAT', 'items': ['11013331', '9843236'] }, { 'type': 'NOT', 'items': ['9085267', '11788544'] }, { 'type': 'ETH', 'items': ['5238761', '962142', '7795297', '7341464', '5594916', '1550003'] }, ]
Solution:
Step 1: Create a Dictionary
Step 2: Convert to Expected Format
Example Code:
<code class="python">from collections import defaultdict res = defaultdict(list) for v, k in input: res[k].append(v) output = [{'type': k, 'items': v} for k, v in res.items()]</code>
Alternative Solution using itertools.groupby:
Note: This approach requires the input to be sorted.
Example Code:
<code class="python">from itertools import groupby, itemgetter sorted_input = sorted(input, key=itemgetter(1)) groups = groupby(sorted_input, key=itemgetter(1)) output = [{'type': k, 'items': [x[0] for x in v]} for k, v in groups]</code>
Note on Key Order:
The above is the detailed content of Here\'s a suitable title for your article, keeping the question format in mind: How to Group Data Pairs by Type in Python: Efficient Solutions with `defaultdict` and `itertools.groupby`. For more information, please follow other related articles on the PHP Chinese website!