python字典:指定空白字典
为什么以下代码会出现以下错误,以及如何将其分配给函数中的空白字典:python字典:指定空白字典,python,dictionary,Python,Dictionary,为什么以下代码会出现以下错误,以及如何将其分配给函数中的空白字典: import time dictionary_power_readings = {} def update_dict(): ApparentPower = "power" dictionary_power_readings[time.time()] = ApparentPower print(dictionary_power_readings) dictionary_po
import time
dictionary_power_readings = {}
def update_dict():
ApparentPower = "power"
dictionary_power_readings[time.time()] = ApparentPower
print(dictionary_power_readings)
dictionary_power_readings ={}
while True:
update_dict()
time.sleep(1)
回溯(最近一次调用上次):文件
“从_function.py更新_dict_”,中第15行
update_dict()文件“从_function.py更新_dict”,第7行,在update_dict中
dictionary\u power\u readings[time.time()]=ApparentPower UnboundLocalError:局部变量“dictionary\u power\u readings”
分配前参考
在函数中使用全局关键字
def update_dict():
global dictionary_power_readings
ApparentPower = "power"
dictionary_power_readings[time.time()] = ApparentPower
print(dictionary_power_readings)
dictionary_power_readings ={}
它可以工作,只需在函数中尝试一次
global dictionary\u power\u reads
,或者使用上面注释中提到的global
,或者更好:将字典作为参数传递到函数中。代码将更易于测试、扩展和阅读。@rdas和@yedpodtrzitko的答案是正确的。但是我想知道这段代码和字典\u power\u读物的目的是什么
?谢谢你的回答。我简化了堆栈溢出问题,因此代码的目标可能对您没有意义。总之,我正在处理从MQTT代理接收的数据,并将在数据流上运行机器学习模型。对我来说没有意义的是,我可以使用“dictionary\u power\u readings[time.time()]=ApparentPower”行更新变量,但不能将其设置为空。为什么?你不能只使用time.time(),因为它是float而不是int。试试这个dictionary\u power\u readings[int(time.time())]=ApparentPower
def update_dict():
global dictionary_power_readings
ApparentPower = "power"
dictionary_power_readings[time.time()] = ApparentPower
print(dictionary_power_readings)
dictionary_power_readings ={}