繁体   English   中英

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

[英]Convert a text file in to a dictionary in python

在此处输入图像描述

在尝试将文本文件转换为字典时,我在 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 个值才能解压

这是一个简单的 function 打开 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 获取文件,您实际上可以使用 requests 库直接获取它:

安装:

pip install requests

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

import requests

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM