Python 如何使用密钥从JSON文件中获取值?

Python 如何使用密钥从JSON文件中获取值?,python,json,dictionary,Python,Json,Dictionary,我是python新手。我试图从JSON文件中获取值 这是存储在static/tokens.JSON中的JSON文件 { "872387":"ABC", "821483":"XYZ", "575652":"KLM" } 我想读取并获取键821483的值。这就是XYZ 这就是我正在做的 我正在读Json文件 token = json.load(open(os.path

我是python新手。我试图从JSON文件中获取值

这是存储在static/tokens.JSON中的JSON文件

{
  "872387":"ABC",
  "821483":"XYZ",
  "575652":"KLM"
}
我想读取并获取键821483的值。这就是XYZ

这就是我正在做的

我正在读Json文件

token = json.load(open(os.path.join(app.root_path, "static", "tokens.json")))
print(token['821483'])
但它给了我一个错误:

print(token['821483']) TypeError: string indices must be integers
我也试过这个

with open(os.path.join(app.root_path, "static", "tokens.json")) as read_file:
  data = json.load(read_file)[1]
print("Type of deserialized data: ", type(data))
print(data['821483'])
但我又犯了同样的错误

我在Stackoverflow上看到过类似的问题。到目前为止我所理解的是

tokens = json.load(open(os.path.join(app.root_path, "static", "tokens.json"))) converts Json to a List. How can I solve this problem? I don't want to change the structure of JSON file.
如何将此JSON文件转换为字典而不是列表,以便使用键访问值?

使用JSON.load时,python会自动转换为dict,因此无需再次转换为dict

import json
data = json.load(open("static/tokens.json"))
现在检查数据中的内容和数据类型:

如果不想进行迭代,只需使用dict_object.getvalue即可


令牌的数据类型是什么printtypetokens-或简单的printtokens@第二次世界大战无法复制。第二次世界大战我无法复制。我得到了``token['821483']'XYZ```。您确定tokens.json的结构吗。从您得到的错误来看,我怀疑文件中的JSON实际上是一个对象数组,它转换为JSON.load之后的dict列表。您给出的JSON文件示例不能忠实地表示实际文件。您说过printtypetoken在注释中返回,但问题中包含的异常表明token是字符串。您应该将printtoken的结果添加到您的问题中。我们是否必须在python中迭代字典才能获得值?我希望它能在Java中作为MapKey-Value对工作。不进行迭代是不可能的吗?您可以使用getvalue,检查更新的答案。@RohitSingh-不-非常感谢。它起作用了。不清楚这是如何回答这个问题的,这基本上与OP的示例代码相同。
{'872387': 'ABC', '821483': 'XYZ', '575652': 'KLM'} <class 'dict'>
for key, value in data.items():
    if key == "821483":
        print({key: value})

Out: {'821483': 'XYZ'}
print(data.get("821483"))
Out: XYZ