如何用Python从JSON文件提取dst与value构建指定结构字典?
Solution to Build Dictionary from JSON Data
Got it, let's get your code working to create the dictionary you need. Here's the complete, cleaned-up code with explanations:
import json # Don't forget to import the json module! filename = "your_file.json" # Replace with your actual file path list_dev = {} with open(filename) as feedjson: json_data = json.load(feedjson) # No need for feedjson.close() — the 'with' statement handles closing automatically for item in json_data["index"]: # Convert the 'dst' list to a tuple (since lists can't be dictionary keys) dst_tuple = tuple(item["dst"]) # Assign the 'value' list as the value for this key list_dev[dst_tuple] = item["value"] # Verify the result print(list_dev)
Key Details:
- Import json: Make sure you include this at the top of your script—your partial code didn't mention it, but it's required to parse the JSON file.
- Redundant close call: The
withstatement automatically closes the file once the block finishes, sofeedjson.close()is unnecessary and can be removed. - Tuple conversion: Python lists are unhashable (can't be used as dictionary keys), so we convert the
dstlist to a tuple usingtuple(item["dst"])to make it a valid key. - Map values: For each entry in the
indexarray, we link the tuple version ofdstto its correspondingvaluelist in the dictionary.
Running this code will produce exactly the structure you want:
{(1, 2, 5): [0], (1, 2, 4): [2]}
内容的提问来源于stack exchange,提问作者AhmyOhlin
相关产品推荐
相关产品推荐

