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

如何将含字典元素的一维数组转换为二维数组(不使用numpy/pandas)

将含字典的一维数组转为二维数组(无需numpy/pandas)

实现思路

针对输入的单字典数组:

  1. 提取数组中的字典元素
  2. 把字典的键作为二维数组的表头行
  3. 把字典的值作为二维数组的数据行
  4. 将表头行和数据行组合成最终的二维数组

代码实现

首先定义输入数组:

array = [{"id": "123", 'name-code': 'user-1666935009', 'r.no.': '1', 'start_time': '1666955702', 'state_msg': 'Finished', 'state_details': '', 'setup_time': '2371'}]

转换代码:

# 取出数组中的字典
target_dict = array[0]
# 生成表头行(字典的键)
header_row = list(target_dict.keys())
# 生成数据行(字典的值)
data_row = list(target_dict.values())
# 组合成二维数组
result_array = [header_row, data_row]

执行后,result_array就是你需要的输出:

[['id','name-code','r.no.','start_time','state_msg','state_details','setup_time'],['123','user-1666935009', '1','1666955702','Finished','','2371']]

扩展:处理多字典数组

如果输入数组包含多个字典元素,只需循环遍历每个字典,依次添加数据行即可:

# 多字典输入示例
array = [
    {"id": "123", 'name-code': 'user-1666935009', 'r.no.': '1', 'start_time': '1666955702', 'state_msg': 'Finished', 'state_details': '', 'setup_time': '2371'},
    {"id": "456", 'name-code': 'user-1666935010', 'r.no.': '2', 'start_time': '1666955802', 'state_msg': 'Running', 'state_details': 'In progress', 'setup_time': '1890'}
]

# 生成表头
header_row = list(array[0].keys())
result_array = [header_row]
# 遍历所有字典,添加数据行
for item in array:
    result_array.append(list(item.values()))

内容的提问来源于stack exchange,提问作者Aditi Pathak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:50:26