如何将Python字符串转换为字典?[duplicate]

wqlqzqxt  于 2023-02-26  发布在  Python
关注(0)|答案(2)|浏览(139)
    • 此问题在此处已有答案**:

How to dump a dict to a JSON file?(7个答案)
5天前关闭。
如何将某个变量(字符串)添加到一个全新的字典中,然后解析到另一个名为 * cars. json * 的文件中?程序会询问用户一些关于他们的汽车的问题,然后每个变量都应该解析到一个字典中。项目名称应该是预先设置的,比如型号,值应该是变量。
这是我尝试过的。

  • 汽车. py *
class CarCreator:
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color
  • 主文件. py *
from cars import CarCreator

carVarAtt = CarCreator(None, None, None, None)

with open("./cars.json", "a") as f:
            carVarMake = input("What is the make of your car? (Ford, Honda, Etc...)\n")
            carVarModel = input("What is the model of your car? (Focus, Civic, Etc...)\n")
            carVarYear = input("What is the year of your car? (2018, 2019, Etc...)\n")
            carVarColor = input("What is the color of your car? (Red, Blue, Etc...)\n")

            carVarAtt.make = carVarMake
            carVarAtt.model = carVarModel
            carVarAtt.year = carVarYear
            carVarAtt.color = carVarColor

            carVarName = f'"{carVarMake} {carVarModel}"'

            f.write("{\n")

            f.write(f"    {carVarName}: ")
            f.write("{\n")
            f.write(f'        "Make": "{carVarMake}",\n')
            f.write(f'        "Model": "{carVarModel}",\n')
            f.write(f'        "Year": {carVarYear},\n')
            f.write(f'        "Color": "{carVarColor}"\n')

            if f is None:
                f.write("    },\n")
            elif f is not None:
                f.write("    }\n")
            
            f.write("}")

我不需要写所有这些f.write(),而是需要取carVarMakecarVarModel等,并将它们赋给字典中的条目。是否已经有库或内置的Python函数可以实现这一点,还是需要手动完成?

g2ieeal7

g2ieeal71#

使用从用户输入中获得的信息,可以创建一个Python字典,这些字典可以使用Python中的json模块存储在JSON文件中。

import json

# Your code for getting user input comes here

cars = {}
cars[carVarName] = {
    "Make": carVarMake,
    "Model": carVarModel,
    "Year": carVarYear,
    "Color": carVarColor
}
with open("./cars.json", "a") as file:
    json.dump(cars, file)

注意,这里我已经将文件写入移到了输入收集发生的地方之外。您可以忽略这个更改,并保持之前的结构。只要您将信息保存到Python字典中,json模块可以非常容易地将字典保存为JSON文件格式。您不需要安装这个模块,因为它是内置的。

ufj5ltwl

ufj5ltwl2#

您只需稍微更改代码:

import json
from cars import CarCreator

carVarAtt = CarCreator(None, None, None, None)

carVarMake = input("What is the make of your car? (Ford, Honda, Etc...)\n")
carVarModel = input("What is the model of your car? (Focus, Civic, Etc...)\n")
carVarYear = input("What is the year of your car? (2018, 2019, Etc...)\n")
carVarColor = input("What is the color of your car? (Red, Blue, Etc...)\n")

carVarAtt.make = carVarMake
carVarAtt.model = carVarModel
carVarAtt.year = carVarYear
carVarAtt.color = carVarColor

new_data = {
    f"{carVarMake} {carVarModel}": {
        "Make": f"{carVarMake}",
        "Model": f"{carVarModel}",
        "Year": f"{carVarYear}",
        "Color": f"{carVarColor}",
    }
}

with open("./cars.json", "r") as data_file:
    data = json.load(data_file)

data.update(new_data)
with open("./cars.json", "w") as data_file:
    json.dump(data, data_file, indent=4)

注意,我更喜欢在阅读模式下打开文件,将内容保存到一个变量中,然后更新变量以添加新内容,最后在写模式下打开文件,“转储”所有内容。如果文件还不存在,这可能会导致错误。在这种情况下,您可以使用以下命令:

try:
    with open("./cars.json", "r") as data_file:
        data = json.load(data_file)
except FileNotFoundError:
    with open("./cars.json", "w") as data_file:
        json.dump(new_data, data_file, indent=4)
else:
    data.update(new_data)
    with open("./cars.json", "w") as data_file:
        json.dump(data, data_file, indent=4)

如果这太多了,那么使用appending也没有什么错。

with open("./cars.json", "a") as data_file:

现在,如果你必须为你创建的每个新的汽车对象都这样做,我建议你在类CarCreator中创建一个方法来请求用户输入,以及另一个方法来生成字典并将其添加到JSON文件中,然后你可以根据需要在你的www.example.com中调用这些方法main.py。
此外,如果您希望遵循python代码约定,则应该只为类(myClass)保留camel大小写,而为变量(my_variable)使用snake大小写。
编程命名约定
Name conventions in python

相关问题