【问题标题】:Build Nested Dictionary at run time in Python在 Python 中运行时构建嵌套字典
【发布时间】:2015-01-12 12:45:02
【问题描述】:

我想像这样在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'}}

【问题讨论】:

  • missing temp = {} 声明移到循环内。
  • 你能不能再正确打印一遍o/p,我没听懂
  • 在我看来你得到了正确的输出。那里有什么问题?您希望输出按特定顺序排列吗?
  • @thiruvenkadam 看到我一次又一次地得到同一行,请注意 unique_arguments。

标签: python dictionary


【解决方案1】:

由于这里没有给出答案,我只是在这里给出解释。

在这里,您一次又一次地替换临时字典。当您执行 log_dictionary[row[0]] = temp 时,这只是指向现有的 temp 字典。因此,每当您更改临时字典中的任何值并阅读 log_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

这将为您提供更新的临时字典值,因为它只是被 log_dictionary 引用。正如 Ashwini Chaudhary 在您的评论中提到的,如果您在将临时字典引用到 log_dictionary 之前在 for 循环中初始化临时字典,您将获得所需的值。 (例如)

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

【讨论】:

    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2021-11-25
    • 2023-01-18
    • 1970-01-01
    相关资源
    最近更新 更多