【发布时间】:2021-08-30 06:23:31
【问题描述】:
我想用 for 循环的类实例填充字典,每个实例都有带有消息的列表,如果已经有具有相同 id 的实例,则将消息插入到其列表中。
我正在使用的 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
我的代码:
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 的特定实例并将值附加到其列表中?
感谢您的帮助!
【问题讨论】:
-
好的,现在应该没问题了。
-
您能否也添加一个示例输入和输出
-
我重新格式化您的代码。核实。您能否使用
df.head().to_dict()的输出更新您的帖子作为您的数据框样本? -
我添加了我正在使用的 csv 文件的示例以及我创建并从中填充类属性的 pandas 数据框
标签: python pandas dictionary oop