You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现:向字典中指定ID的类实例消息列表追加数据

Problem

我希望通过for循环构建一个字典,其中字典的每个值为MessageID类的实例,每个实例包含一个存储消息的列表。具体需求为:若字典中已存在对应ID的MessageID实例,则将新消息插入该实例的列表中;若不存在,则创建新的MessageID实例,将消息添加到其列表后存入字典。

CSV文件内容

time,ID,TYPE,Source
2021-07-26T23:59:59.143,112233449955,TYPE1,SOURCE1
2021-07-26T23:59:57.146,112233449955,TYPE2,SOURCE3
2021-07-26T23:59:56.148,233445522112,TYPE1,SOURCE2
2021-07-26T23:59:55.120,333333333333,TYPE2,SOURCE2
2021-07-26T23:59:52.130,444444444444,TYPE1,SOURCE14
2021-07-26T23:59:51.132,333333333333,TYPE3,SOURCE4

现有代码

import pandas as pd

data = pd.read_csv('data.csv', dtype=str)
df = pd.DataFrame(data, columns=['time', 'ID', 'TYPE', 'Source'])

class MessageID:
    time = None
    myid = None
    def __init__(self):
        self.messages= []

class Message:
    time = None
    myid = None
    mytype = None
    source = None
    def __init__(self, time, myid, mytype, source):
        self.time = time
        self.myid = myid
        self.mytype = mytype
        self.source= source

MessageID_dictionary= {}

for index, row in df.iterrows():
    newMessage = Message(row['time'], row['ID'], row['TYPE'], row['Source'])
    # is id already in dictionary? then add newMessage.__dict__ to the list of instance with the found id
    if newMessage.myid in MessageID_dictionary.keys():
        MessageID_dictionary[newMessage.myid] = [MessageID_dictionary[newMessage.myid], newMessage.__dict__]
        #Here I do not know how to find the particular instance with the found id (newMessage.id) and append to its list but not directly to the dictionary to the instance of the MessageID's
        print('yes')
    #if there is not the found id then create the instance of MessageID, append the newMessage to list of the instance and add the instance to the dictionary
    else:
        newMessageID = MessageID()
        newMessageID.messages.append(newMessage.__dict__)
        MessageID_dictionary[newMessage.myid] = newMessage.__dict__
        print('no')

print(MessageID.dictionary)
print(newMessage.messages)

我的疑问

是否可以找到字典中指定ID对应的MessageID类实例,并向该实例的messages列表追加值?恳请各位提供帮助!


Solution

当然可以实现你的需求,先帮你指出现有代码里的几个关键问题:

  1. 在else分支里,你错误地把newMessage.__dict__存入了字典,而不是刚创建的newMessageID实例——这就导致字典里根本没有存储MessageID对象,后续自然无法找到实例去追加消息。
  2. 在if分支里,你尝试把现有值和新消息组成列表赋值给字典,这会破坏原来的MessageID实例结构,正确的做法应该是直接获取字典里的MessageID实例,然后调用它的messages.append()方法。

下面是修正后的完整代码,我会逐步解释:

import pandas as pd

data = pd.read_csv('data.csv', dtype=str)
df = pd.DataFrame(data, columns=['time', 'ID', 'TYPE', 'Source'])

class MessageID:
    def __init__(self):
        # 这里不需要类属性time和myid,因为字典的key已经是ID了,实例里无需重复存储
        self.messages = []

class Message:
    def __init__(self, time, myid, mytype, source):
        self.time = time
        self.myid = myid
        self.mytype = mytype
        self.source = source

MessageID_dictionary = {}

for index, row in df.iterrows():
    newMessage = Message(row['time'], row['ID'], row['TYPE'], row['Source'])
    message_id = newMessage.myid
    
    # 检查ID是否已在字典中
    if message_id in MessageID_dictionary:
        # 直接获取对应的MessageID实例,追加新消息到它的messages列表
        existing_instance = MessageID_dictionary[message_id]
        existing_instance.messages.append(newMessage)
        print(f"已向ID {message_id} 的实例追加消息")
    else:
        # 创建新的MessageID实例,添加消息后存入字典
        new_instance = MessageID()
        new_instance.messages.append(newMessage)
        MessageID_dictionary[message_id] = new_instance
        print(f"为ID {message_id} 创建新实例并添加消息")

# 验证结果:遍历字典,打印每个ID对应的所有消息
for msg_id, msg_id_instance in MessageID_dictionary.items():
    print(f"\nID: {msg_id}")
    for msg in msg_id_instance.messages:
        print(f"  时间: {msg.time}, 类型: {msg.mytype}, 来源: {msg.source}")

关键修正点说明:

  • 移除了MessageID类中不必要的类属性time和myid,因为字典的key已经是消息ID,不需要在实例里重复存储。
  • else分支中,将创建好的new_instance存入字典,而不是newMessage.__dict__,这样字典里保存的才是MessageID实例,后续才能直接操作它的messages列表。
  • if分支中,直接通过MessageID_dictionary[message_id]获取到对应的MessageID实例,然后调用messages.append(newMessage)就能把新消息添加到实例的列表中,完全符合你的需求。
  • 最后添加了验证代码,方便你查看每个ID对应的所有消息,确认结果是否正确。

如果你不需要把整个Message对象存入列表,而是只需要它的字典形式(像你原来代码里的newMessage.__dict__),只需要把append(newMessage)改成append(newMessage.__dict__)即可。

内容的提问来源于stack exchange,提问作者vloubes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 09:42:32