Python中如何使用map函数将指定元组列表转换为目标字典?
How to use
map() to transform the list into a grouped dictionary Given your input list:
x = [('a',11),('a',12),('b',13),('b',14)]
There are a couple of ways to use map() to get the desired output {'a':[11,12], 'b':[13,14]}, though we’ll need to combine it with other tools since map() alone can’t handle grouping values by key.
Approach 1: Using itertools.groupby (Functional, Preferred)
This method aligns with functional programming practices and avoids side effects. Here’s how it works:
- Sort the input list: First, we sort the list by the key (the first element of each tuple) because
groupbyonly groups consecutive elements with the same key. - Group by key: Use
itertools.groupbyto create groups of tuples sharing the same key. - Map groups to key-value pairs: Use
map()to convert each group into a tuple where the key is the group’s identifier, and the value is a list of the corresponding numbers. - Convert to dictionary: Turn the result of
map()into a dictionary.
Here’s the code:
import itertools x = [('a',11),('a',12),('b',13),('b',14)] # Sort the list to ensure same keys are grouped consecutively sorted_x = sorted(x, key=lambda item: item[0]) # Group by the first element of each tuple, then map groups to (key, value list) grouped = itertools.groupby(sorted_x, key=lambda item: item[0]) x_map = dict(map(lambda group: (group[0], [num for (_, num) in group[1]]), grouped)) print(x_map) # Output: {'a': [11, 12], 'b': [13, 14]}
Approach 2: Using collections.defaultdict (Side Effect-Based)
This approach uses map() for its side effect of appending values to a dictionary’s lists. While it works, it’s not the most idiomatic use of map() since it relies on mutating state:
from collections import defaultdict x = [('a',11),('a',12),('b',13),('b',14)] x_map = defaultdict(list) # Use map to append each value to the corresponding key's list list(map(lambda item: x_map[item[0]].append(item[1]), x)) # Convert to a regular dict if needed (optional) x_map = dict(x_map) print(x_map) # Output: {'a': [11, 12], 'b': [13, 14]}
Notes:
- Approach 1 is better if you prefer functional programming and want to avoid modifying variables in place.
- Approach 2 is shorter but uses
map()for side effects, which isn’t the primary purpose of the function.
内容的提问来源于stack exchange,提问作者Karthik Prabhu
相关产品推荐
相关产品推荐

