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

如何用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 with statement automatically closes the file once the block finishes, so feedjson.close() is unnecessary and can be removed.
  • Tuple conversion: Python lists are unhashable (can't be used as dictionary keys), so we convert the dst list to a tuple using tuple(item["dst"]) to make it a valid key.
  • Map values: For each entry in the index array, we link the tuple version of dst to its corresponding value list in the dictionary.

Running this code will produce exactly the structure you want:

{(1, 2, 5): [0], (1, 2, 4): [2]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:28:44