简体   繁体   English

将嵌套字典中的numpy数组转换为列表,同时保留字典结构

[英]Convert numpy arrays in a nested dictionary into list whilst preserving dictionary structure

I am looking for a way how to dump nested dictionary containing numpy arrays into JSON file (to keep full logs of my experiments and data in one place). 我正在寻找一种方法如何将包含numpy数组的嵌套字典转储到JSON文件中(以便将我的实验和数据的完整日志保存在一个地方)。

My dictionary looks like this (the structure may be more nested than the code displayed): 我的字典看起来像这样(结构可能比显示的代码更嵌套):

import numpy as np
data = {'foo': {'bar': np.array([1, 2, 3])}, 'goo': np.array([3,5,7]),'fur': {'dur': {'mur': np.array([7,5,8])}}}

At the moment this code fails because numpy array is not serializable: 此代码失败,因为numpy数组不可序列化:

with open('data.txt','w') as fl:
    json.dump(data,fl)

I know it is possible to use tolist() function but I do not know how to walk over the dictionary whilst preserving the structure of data and exchanging np.arrays for list. 我知道可以使用tolist()函数,但我不知道如何在保留数据结构和交换np.arrays列表的同时遍历字典。

I tried getting individual values from the dictionary using recursion but I do not know how to "build the dictionary back". 我尝试使用递归从字典中获取单个值,但我不知道如何“构建字典”。 My code at the moment (without json dump): 我的代码(没有json转储):

import numpy as np

def dict_walk(data):
    for k, v in data.iteritems():
        if isinstance(v, dict):
            dict_walk(v)
        else:
            l = v.tolist()
            print l

data = {'foo': {'bar': np.array([1, 2, 3])}, 'goo': np.array([3,5,7]),'fur': {'dur': {'mur': np.array([7,5,8])}}}
dict_walk(data)       

You can give json.dump a default function; 你可以给json.dump一个default函数; it is called for any data type that JSON doesn't know how to handle: 它被调用JSON不知道如何处理的任何数据类型:

def default(obj):
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    raise TypeError('Not serializable')

with open('data.txt','w') as fl:
    json.dump(data, fl, default=default)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM