将中的文本文件转换为python中的词典

2024-06-16 11:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

我在python中尝试将文本文件转换为字典时遇到值错误

我正在从api获取该文件

filename=open('/sbranch/CTK/SAP/hkeep/vrp.json','r')
dictionary = {}
with open("/sbranch/CTK/SAP/hkeep/vrp.json", "r") as file:
    for line in file
        key, value = line.strip()
        dictionary[key] = value
    print(dictionary)

以下是错误消息:

key, value = line.strip()

ValueError:需要超过1个值才能解包


Tags: keyjsondictionaryvalue错误lineopenfile
1条回答
网友
1楼 · 发布于 2024-06-16 11:14:22

这是一个打开json文件并将其加载到python字典的简单函数:

import json

def open_json(path):
    with open(path, 'r') as file:
        return json.load(file)

mydict = open_json('/sbranch/CTK/SAP/hkeep/vrp.json')

如果您是从api获取文件,实际上可以使用请求库直接获取:

安装:

pip install requests

这将从json响应中为您提供一个字典(如果有json):

import requests

url = 'enter_your_url_here'
response = requests.get(url)
mydict = response.json()

相关问题 更多 >