如何解决列表在要求这样做之前附加字典
我正在尝试将字典附加到列表中,也就是说,我需要一个字典列表以进行进一步处理。 信息来自电子邮件,因此我使用的是“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
中的当前 orderDict['name']
。如果我还没有打电话给 orderList
,这怎么可能?
解决方法
在您的代码中,您有:
orderDict = {}
for number in range(amountMessages):
...
orderDict['Email'] = email
您每次都更新相同的 dict
。
你应该拥有的是:
for number in range(amountMessages):
orderDict = {}
...
orderDict['Email'] = email
这里每次循环都会重新创建 orderDict
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。