在Python中运行时构建嵌套字典

在Python中运行时构建嵌套字典,python,dictionary,Python,Dictionary,我想用python像这样构建动态字典 users = {log_id : { "message_id" : "1", "sent_to" : "taqi.official@outlook.com" , "unique_arguments" : "03455097679"}, log_id : { "message_id" : "1", "sent_to" : "taqi.hass@cogilent.com" , "unique_arguments" : "03455097679" },

我想用python像这样构建动态字典

users = {log_id : { "message_id" : "1", "sent_to" : "taqi.official@outlook.com" , "unique_arguments" : "03455097679"},
     log_id : { "message_id" : "1", "sent_to" : "taqi.hass@cogilent.com" , "unique_arguments" : "03455097679" },
     log_id : { "message_id" : "2 Turab", "sent_to" : "taqi.official@gmailllllll.com" , "unique_arguments" : "4534534535" }}
我已经写了这段代码,但它不是我想要的建设

cur = conn.cursor()
cur.execute("select log_id, message_id, sent_to, unique_arguments from sendmessage_log_messages where log_status = 'Queue'")
rows = cur.fetchall()
count = 0
for row in rows:
    temp['message_id'] = row[1]
    temp['sent_to'] = str(row[2])
    temp['unique_arguments'] = row[3]
    log_dictionary[row[0]] = temp

print log_dictionary
它产生这个输出的结果

{1: {'unique_arguments': 'log_8_taqi.official@gmailllllll.com', 'message_id': 8, 'sent_to': 'taqi.official@gmailllllll.com'}, 
2: {'unique_arguments': 'log_8_taqi.official@gmailllllll.com', 'message_id': 8, 'sent_to': 'taqi.official@gmailllllll.com'}, 
3: {'unique_arguments': 'log_8_taqi.official@gmailllllll.com', 'message_id': 8, 'sent_to': 'taqi.official@gmailllllll.com'}, 
4: {'unique_arguments': 'log_8_taqi.official@gmailllllll.com', 'message_id': 8, 'sent_to': 'taqi.official@gmailllllll.com'}}

既然这里没有答案,我就在这里解释一下

在这里,您一次又一次地替换临时字典。当您执行log_dictionary[row[0]]=temp时,它只指向现有的temp dictionary。因此,每当您更改临时字典中的任何值并阅读日志字典时,这将始终只提供更新的临时字典

试试这个:

for row in rows:
    temp['message_id'] = row[1]
    temp['sent_to'] = str(row[2])
    temp['unique_arguments'] = row[3]
    log_dictionary[row[0]] = temp
print log_dictionary
temp['message_id'] = 0
temp['send_to'] = 'stackoverflow'
temp['unique_arguments'] = None
print log_dictionary
这将为您提供更新的临时字典值,因为它刚刚被日志字典引用。正如Ashwini Chaudhary在您的评论中提到的,如果您在引用for循环中的临时字典到log_dictionary之前对其进行初始化,您将获得所需的值。乙二醇

for row in rows:
    temp = {}
    temp['message_id'] = row[1]
    temp['sent_to'] = str(row[2])
    temp['unique_arguments'] = row[3]
    log_dictionary[row[0]] = temp

将缺少的temp={}声明移到循环中。你能再次正确打印o/p吗?我不明白。在我看来,你的输出是正确的。有什么问题吗?你想让输出按那个特定的顺序吗?@thiruvenkadam看到我一次又一次地得到同一行,请注意唯一的_参数。