【问题标题】:Python: First Object from a JsonPython:来自 Json 的第一个对象
【发布时间】:2021-06-01 18:06:46
【问题描述】:

我有一个带有一些环境变量的 Json 文件,我想将其加载到我的程序中,使用它们或更改它们。之后我想将变量也保存到 json 中。

为此,我创建了一个如下所示的 Json 文件:

{"1": { "Farbe": "weiss", "Gewicht": "1000", "Preis":30},"2"{....}

现在我正在尝试打开文件并打印值“Farbe”。

f = open(my_file)
    filament = json.load(f)
    f.close()
    print (filament)
    pairs = filament.items()
    for key, value in pairs:
        x = key
    print (x)
    i=1
    while i <= len(key):
        print ("\t",i,".) ",filament[i]['Farbe']"\n")
        i=i+1

但是当我尝试使用我喜欢 Filament[i] 的变量来获取我的值时,我无法得到这样的错误:Traceback (most recent call last): File "F:\Python\Tutorial\Datei_druckkosten.py", line 49, in &lt;module&gt; print ("\t",i,".) ",filament[i]['Farbe']) KeyError: 1

我希望我的结果看起来像这样:

1.) 韦斯 2.) 别的东西 ....

有人可以帮忙吗?

【问题讨论】:

  • 你的问题不清楚。您能否详细说明预期的结果应该是什么?
  • 你为什么要遍历字典两次?

标签: python arrays json python-3.x


【解决方案1】:

您必须转换为 enter code herefilament[i]['Farbe'] 一世 串起来 enter code herefilament[str(i)]['Farbe'] 并添加逗号 enter code herefilament[i]['Farbe'], "\n"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多