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

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:

  1. Sort the input list: First, we sort the list by the key (the first element of each tuple) because groupby only groups consecutive elements with the same key.
  2. Group by key: Use itertools.groupby to create groups of tuples sharing the same key.
  3. 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.
  4. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:31:18