我想要實作的是一個字典,其中包含作為鍵的傳感器和作為值的字典串列。字典串列的格式必須為 {"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)
但每個附加似乎都繼續到所有鍵。這是終端的結果:
{'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}]}
一些幫助將不勝感激。
uj5u.com熱心網友回復:
附加到一個串列似乎會附加到所有串列,因為它們都是同一個串列!您可以通過 來檢查它id(my_dict['humidity']) == id(my_dict['temperature']),它給出了True.
您需要為每個鍵創建一個新串列,因此請執行以下操作:
my_dict = {s: [] for s in my_sensors}
uj5u.com熱心網友回復:
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() 函式中的空串列 ([]) 是默認為每個鍵提供的單個串列。
uj5u.com熱心網友回復:
來自https://docs.python.org/3/library/stdtypes.html:
類方法 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 作為諸如空串列之類的可變物件通常是沒有意義的。要獲得不同的值,請改用 dict 理解。
重要的是要注意以下宣告:“所有值僅指一個實體”
您可以通過獲取值的地址來驗證它:
print(id(my_dict['temperature']))
print(id(my_dict['humidity']))
2606880003968
2606880003968
您應該使用 dict 理解來創建您的字典,例如:
my_dict = dict([(sensor, []) for sensor in my_sensors])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471994.html
上一篇:Python:在字典中排序和求和
