numpy保存和读取dictionary字典 python

It is very important for training to record the parameters or data!

Code

	import numpy as np
	# define
	dict = {'a' : {1,2,3}, 'b': {4,5,6}}
	# save
	np.save('dict.npy', dict)
	# load
	dict_load=np.load('dict.npy', allow_pickle=True)
	
	print("dict =", dict_load.item())
	print("dict['a'] =", dict_load.item()['a'])

output:

dict = {'a': {1, 2, 3}, 'b': {4, 5, 6}}
dict['a'] = {1, 2, 3}

References

Note

numpy.savez is also a interesting method, you could use it to record the specific array with keywords like dict. The type of file is .npz

  • Example
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> y = np.sin(x)

>>> np.savez(outfile, x=x, y=y)
>>> npzfile = np.load(outfile)
>>> npzfile.files
['x', 'y']
>>> npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

from numpy.savez

  • 17
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要将Python字典存入NumPy数组中,可以使用NumPy的save函数将字典保存为.npy文件,然后使用load函数加载.npy文件。以下是一个示例代码: ``` import numpy as np my_dict = {'a': {1, 2, 3}, 'b': {4, 5, 6}} np.save('dict.npy', my_dict) loaded_dict = np.load('dict.npy', allow_pickle=True).item() print("Original dictionary:", my_dict) print("Loaded dictionary:", loaded_dict) ``` 这段代码将字典`my_dict`保存为名为'dict.npy'的.npy文件,然后使用`np.load`函数加载.npy文件并将其转换回字典格式。最后打印出原始字典和加载后的字典。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [numpy保存读取dictionary字典 python](https://blog.csdn.net/weixin_45366564/article/details/104667150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [python使用numpy保存字典格式的数据](https://blog.csdn.net/weixin_35757704/article/details/124921501)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值