python - 列表在被要求这样做之前附加字典
问题描述
我正在尝试将字典附加到列表中,也就是说,我需要一个字典列表以进行进一步处理。这些信息来自电子邮件,所以我使用的是“ezgmail”模块。
发生的事情是上述列表中的意外行为,在我要求它这样做之前它似乎已更新。让我们从一个例子开始,这样我可以更好地理解自己。
如果我做:
listdict = []
dictname = {'name':'John'}
listdict.append(dictname)
dictname = {'name':'Sarah'}
listdict.append(dictname)
print(listdict)
[{'name': 'John'}, {'name': 'Sarah'}]
这是完全正常的,也是预期的结果。但这就是在我的真实案例中发生在我身上的事情:
### Here I search for unread emails with ezgmail.search, then get the amount of unread messages with the same subject, and verify whether there are unread messages or not and how many there are, then:
###
orderDict = {}
orderList = []
for number in range(amountMessages):
message = orderEmails[0].messages[number] # fetches the specific message as a message object
stringMessage = str(message) # converts message object to string, needed for re.findall
stringName = re.search("(Name: )+(\w+\s\w+)", stringMessage) # finds Name: xxx and separates both parts
creating a tuple inside a list
name = stringName.group(2)
orderDict['Name'] = name
stringEmail = re.findall("([a-zA-Z0-9._%+-]+@+[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))", stringMessage) #
finds email addresses
tempEmailtuple = stringEmail[2] # it is always email #3 what we need
email = tempEmailtuple[0] # the first part of the tuple contains the whole email address
orderDict['Email'] = email
orderList.append(orderDict)
当我这样做时,我观察到只附加了最后一条消息的信息。考虑到我是新手并且可能搞砸了,我决定在 Python 控制台中手动完成所有操作,而不是使用 for 循环,只需使用字典中的“名称”键。
message = orderEmails[0].messages[0]
stringMessage = str(message)
stringName = re.search("(Name: )+(\w+\s\w+)", stringMessage)
name = stringName.group(2)
orderDict['Name'] = name
orderList.append(orderDict)
#so far so good, but
message = orderEmails[0].messages[1]
stringMessage = str(message)
stringName = re.search("(Name: )+(\w+\s\w+)", stringMessage)
orderDict['Name'] = name
这就是魔法发生的地方。使用时PyCharm
,我可以清楚地看到,在这个确切的时刻orderList
是用当前value
的 in更新的orderDict['name']
。这怎么可能,如果我还没有打电话orderList
呢?
解决方案
当在您的代码中,您有:
orderDict = {}
for number in range(amountMessages):
...
orderDict['Email'] = email
dict
您每次都在更新相同的内容。
你应该拥有的是:
for number in range(amountMessages):
orderDict = {}
...
orderDict['Email'] = email
在这里,您orderDict
每次都通过循环重新创建。
推荐阅读
- asp.net - 跨域请求被阻止:同源策略不允许读取远程资源?
- r - 如何在 as.factor() 中使用空格分隔的变量名来访问数据框的数据?
- vhdl - 由 while 循环创建的综合中的 VHDL 错误
- flash - 如何将 Ruffle flash player 模拟器嵌入 HTML 文件?
- javascript - 如果 Sequelize 中不存在嵌套记录,如何获取所有记录
- javascript - JQM DOM 缓存究竟是什么时候清空的?
- google-sheets - 搜索两个不同的列,如果匹配则复制值
- spring - 如何从 WSS 重定向到 WS?
- php - PHP else/if 语句,带有 rand()
- visual-studio-code - 用于启动配置的文件中的变量