You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何将np.loadtxt导入的array格式字典数据转换为独立dict?

Solution to Convert Numpy Array of String Fragments to Dictionary

Got it, let's fix this step by step. The issue here is that np.loadtxt splits your dictionary string into separate elements in the array because it treats spaces as delimiters by default. Here's how you can turn that array into a proper Python dictionary:

Step 1: Load the data correctly

First, load the file as an array of string fragments (using dtype=str instead of dtype=dict, since np.loadtxt can't directly parse dictionaries this way):

import numpy as np
# Load the file content as an array of string pieces
stock_array = np.loadtxt("wh_stock.dat", dtype=str)

Step 2: Reconstruct the JSON string and convert to dictionary

Use Python's built-in json module to parse the reconstructed string into a dictionary:

import json
# Join all string fragments into one valid JSON-formatted string
full_dict_string = ''.join(stock_array)
# Convert the JSON string to a Python dictionary
stock_dict = json.loads(full_dict_string)

Verify the result

If you print stock_dict, you'll get the standalone dictionary you need:

print(stock_dict)
# Output:
# {"01": 115, "02": 34, "03": 350, "04": 273, "05": 922, "06": 844, "07": 575, "08": 523, "09": 179, "10": 676, "11": 825, "12": 693, "13": 632, "14": 195, "15": 692, "16": 956, "17": 619, "18": 588, "19": 580, "20": 648}

Why this works

Your .dat file contains a single JSON-formatted string, but np.loadtxt splits it into multiple elements whenever it encounters a space. By joining all those fragments back together, you create a valid JSON string that the json module can easily parse into a proper dictionary.

内容的提问来源于stack exchange,提问作者Freya Haslam

火山引擎 最新活动