简体   繁体   中英

Convert a text file in to a dictionary in python

enter image description here

I am getting value error in python while trying to convert a text file in to dictionary.

I am getting the file from an 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)

below is the error message:

key, value = line.strip()

ValueError: need more than 1 value to unpack

This is a simple function to open a json file and load it into a python dictionary:

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')

If you are getting the file from an api, you can actually get it directly using the requests library:

Install:

pip install requests

This will give you a dictionary from the json response (if there is json):

import requests

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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