如何在Python中通过map创建字典?代码输出异常求助
问题分析与解决方案
核心问题
- map函数调用错误:你写的
map(cat(i), randomlist)是错误用法——map的第一个参数应该是函数对象(比如cat),而非函数调用的结果(cat(i)会直接执行,还会因i未定义报错)。 - map返回迭代器而非目标字典:即使修正map调用,它返回的是一个迭代器对象(所以输出
<map at ...>),且迭代器中的元素是40个独立的小字典,不是你需要的“三个键各对应40个值”的大字典。
修正后的代码方案
方案一:纯Python实现(无额外依赖)
import random import xarray as xr catchments = 40 randomlist = random.sample(range(2, 2100), catchments) path = '/uufs/chpc.utah.edu/common/home/u1265332/sliced_catchments/' def cat(i): catch = xr.open_dataset(path + 'catch_' + str(i) + '.nc') catx = catch.PETNatVeg.mean().values / catch.Prec.mean().values caty = catch.TotalET.mean().values / catch.Prec.mean().values sf = catch.snowfall.mean().values / catch.Prec.mean().values return {'catx': catx, 'caty': caty, 'sf': sf} # 生成所有小字典的列表 result_list = [cat(i) for i in randomlist] # 构建目标字典:每个键对应40个值 final_dict = { key: [item[key] for item in result_list] for key in ['catx', 'caty', 'sf'] } print(final_dict)
方案二:借助pandas简化转换(更简洁)
如果已安装pandas,可以用它快速完成批量数据格式转换:
import random import xarray as xr import pandas as pd catchments = 40 randomlist = random.sample(range(2, 2100), catchments) path = '/uufs/chpc.utah.edu/common/home/u1265332/sliced_catchments/' def cat(i): catch = xr.open_dataset(path + 'catch_' + str(i) + '.nc') catx = catch.PETNatVeg.mean().values / catch.Prec.mean().values caty = catch.TotalET.mean().values / catch.Prec.mean().values sf = catch.snowfall.mean().values / catch.Prec.mean().values return {'catx': catx, 'caty': caty, 'sf': sf} # 生成小字典列表并转成DataFrame,再直接导出为目标格式字典 result_df = pd.DataFrame([cat(i) for i in randomlist]) final_dict = result_df.to_dict('list') print(final_dict)
说明
- 两种方案最终都会生成你需要的字典结构:
{'catx': [值1, 值2, ..., 值40], 'caty': [...], 'sf': [...]} - 方案一逻辑清晰,无需额外依赖;方案二代码更简洁,适合处理批量数据转换场景
内容的提问来源于stack exchange,提问作者Zeeshan Asghar
相关产品推荐
相关产品推荐

