我想要实现的是一个包含传感器作为键和字典列表作为值的字典。字典列表格式必须为{"value": xx,"timestamp": EpochTimeInMs}。循环调用代码以向每个传感器(键)附加新值。最终的结果应该是这样的:
{
"temperature": [
{"value": 10,"timestamp": 1634336087000},
{"value": 11,"timestamp": 1634336088765}
],
"humidity": [
{"value": 90,"timestamp": 1634336087000},
{"value": 95,"timestamp": 1634336088765}
]
}'
为此,我尝试了以下代码:
import time
####################
my_sensors = ["temperature", "humidity"]
my_dict = {}.fromkeys(my_sensors, [])
print(my_dict)
val_template = ["value", "timestamp"]
my_val = {}.fromkeys(val_template)
my_val["timestamp"] = int(time.time()*1000)
print(my_val)
#temperature
my_val["value"] = 1234
print(my_val)
my_dict['temperature'].append(my_val.copy())
#humidity
my_val["value"] = 4321
print(my_val)
my_dict['humidity'].append(my_val.copy())
print(my_dict)
但是每个追加似乎都指向所有键。下面是来自terminal的结果:
{'temperature': [], 'humidity': []}
{'value': None, 'timestamp': 1651676483130}
{'value': 1234, 'timestamp': 1651676483130}
{'value': 4321, 'timestamp': 1651676483130}
{'temperature': [{'value': 1234, 'timestamp': 1651676483130}, {'value': 4321, 'timestamp': 1651676483130}], 'humidity': [{'value': 1234, 'timestamp': 1651676483130}, {'value': 4321, 'timestamp': 1651676483130}]}
如果你能帮助我,我将不胜感激。
添加到一个列表似乎添加到所有列表,因为它们都是相同的列表!您可以通过id(my_dict['humidity']) == id(my_dict['temperature'])
检查这一点,从而得到True
。
你需要为每个键创建一个新的列表,所以这样做:
my_dict = {s: [] for s in my_sensors}
import time
my_sensors = ["temperature", "humidity"]
my_dict = {"temperature":[],"humidity":[]}
val_template = ["value", "timestamp"]
my_val = {"value": None, "timestamp": None}
my_val["timestamp"] = int(time.time()*1000)
#temperature
new_dict = my_val.copy()
new_dict["value"] = 1234
my_dict['temperature'].append(new_dict)
#humidity
new_dict = my_val.copy()
new_dict["value"] = 4321
my_dict['humidity'].append(new_dict)
print(my_dict)
Python内部使用指针。因此,fromkeys()函数中的空列表([])是默认情况下提供给每个键的单个列表。
From https://docs.python.org/3/library/stdtypes.html:
classmethod fromkeys(iterable[, value])
Create a new dictionary with keys from iterable and values set to value. fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance,
所以value是一个可变对象是没有意义的比如一个空列表。要获取不同的值,请使用字典理解。
重要的是要注意语句:">所有的值只引用一个实例">
您可以通过获取值的地址来验证它:
print(id(my_dict['temperature']))
print(id(my_dict['humidity']))
2606880003968
2606880003968
你应该使用字典推导来创建你的字典,如:
my_dict = dict([(sensor, []) for sensor in my_sensors])