首页 > 解决方案 > 列表在被要求这样做之前附加字典

问题描述

我正在尝试将字典附加到列表中,也就是说,我需要一个字典列表以进行进一步处理。这些信息来自电子邮件,所以我使用的是“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呢?

标签: pythonlistdictionary

解决方案


当在您的代码中,您有:

orderDict = {}

for number in range(amountMessages):
    ...
    orderDict['Email'] = email

dict您每次都在更新相同的内容。

你应该拥有的是:

for number in range(amountMessages):
    orderDict = {}
    ...
    orderDict['Email'] = email

在这里,您orderDict每次都通过循环重新创建。


推荐阅读