简体   繁体   English

Python: append字典进入字典列表

[英]Python: append dictionary into dictionary list

What I'm trying to achieve is a dictionary containing sensors as keys and a list of dictionaries as values.我想要实现的是一个包含传感器作为键和字典列表作为值的字典。 The list of dictionary must be formatted {"value": xx,"timestamp": EpochTimeInMs}.字典列表必须格式化为 {"value": xx,"timestamp": EpochTimeInMs}。 The code is called cyclically to append new values to each sensor (key).该代码被循环调用,为每个传感器(键)提供 append 个新值。 The final result should be like this:最后的结果应该是这样的:

{
  "temperature": [
    {"value": 10,"timestamp": 1634336087000},
    {"value": 11,"timestamp": 1634336088765}
  ],
  "humidity": [
    {"value": 90,"timestamp": 1634336087000},
    {"value": 95,"timestamp": 1634336088765}
  ]
}'

To do so, I've tried this code:为此,我尝试了这段代码:

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)

But each append seems to proceed to all keys.但是每个 append 似乎都进入了所有键。 Here is the result from 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}]} 

Some help would be much appreciated.一些帮助将不胜感激。

Appending to one list seems to appends to all lists because they are all the same list!附加到一个列表似乎附加到所有列表,因为它们都是同一个列表! You can check this by id(my_dict['humidity']) == id(my_dict['temperature']) , which gives True .您可以通过id(my_dict['humidity']) == id(my_dict['temperature'])检查它,它给出True

You need to create a new list for every key, so do that:您需要为每个键创建一个列表,所以这样做:

my_dict = {s: [] for s in my_sensors}

From https://docs.python.org/3/library/stdtypes.html :来自https://docs.python.org/3/library/stdtypes.html

classmethod fromkeys(iterable[, value])类方法 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,

so it generally doesn't make sense for value to be a mutable object such as an empty list.因此,将值设置为可变的 object(例如空列表)通常没有意义。 To get distinct values, use a dict comprehension instead.要获得不同的值,请改用字典理解。

Important to note the statement: " All of the values refer to just a single instance "重要的是要注意以下声明:“所有值都仅指一个实例

You can verify it by getting the address of the values:您可以通过获取值的地址来验证它:

print(id(my_dict['temperature']))
print(id(my_dict['humidity']))

2606880003968
2606880003968

You should use dict comprehension to create your dictionary like:您应该使用字典理解来创建您的字典,例如:

my_dict = dict([(sensor, []) for sensor 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 internally uses pointers. Python 内部使用指针。 Hence, the empty list ([]) in the fromkeys() function is a single list that is provided by default to each key.因此,fromkeys() function 中的空列表 ([]) 是默认提供给每个键的单个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM