为什么我得到的对象无法通话?

时间:2019-07-28 10:04:17

标签: python python-3.x

代码:

import json
data=json.load(open("data.json"))
print(data)
data("rain")

给我一​​个错误:

Traceback (most recent call last):  
File "<stdin>", line 1, in <module> TypeError: 'dict' object is not callable

2 个答案:

答案 0 :(得分:2)

您的Python dict语法已关闭。假设您要访问rain的{​​{1}}键,则必须使用data运算符。

[]

Python认为您正在调用函数(使用import json data=json.load(open("data.json")) print(data) data["rain"] # <--- change this ),因此告诉您不能将字典作为函数调用!

答案 1 :(得分:1)

以下两个选项

import json
with open("data.json") as f:
    data = json.load(f)
    rain = data["rain"]  # option 1 assuming you are sure that "rain" is in the dict
    rain = data.get("rain","no rain for you")  # option 2 if you are not sure that "rain" is in the dict