[英]Using variables of equal value as dictionary keys results in overwritten values (Python)
I have a Python dictionary as below: 我有一个Python字典,如下所示:
Mail_Dict = {
MailList0 : CodeList0,
MailList1 : CodeList1,
MailList2 : CodeList2,
MailList3 : CodeList3,
MailList4 : CodeList4
}
The issue is when one of the MailLists have values that are the same as another MailList (ie: MailList0 = 'someone@email.com'
and also MailList1 = 'someone@email.com'
), the keys are treated as equal and CodeList0
gets overwritten by CodeList1
, also making my dictionary shorter in the process. 问题是,当其中一个MailList的值与另一个MailList的值相同时(即:
MailList0 = 'someone@email.com'
以及MailList1 = 'someone@email.com'
CodeList0
MailList1 = 'someone@email.com'
),密钥被视为相等,而CodeList0
被CodeList1
覆盖, CodeList1
也使我的字典更短。
Is there anyway to keep these separate? 无论如何,有什么要分开的? I would think that the same logic for below:
我认为以下相同的逻辑:
a=1
b=1
saving to separate memory addresses and being different from: 保存到单独的内存地址,并且不同于:
a=b=1
would apply here, but I guess that isn't the case =( 会在这里适用,但我想并非如此=(
Thanks in advance. 提前致谢。
If you want to create both the values of the same key in the dictionary, one solution would be to add the old value to a list and append the new value to the list. 如果要在字典中创建同一个键的两个值,一种解决方法是将旧值添加到列表中,然后将新值追加到列表中。
Mail_Dict = {
MailList0 : CodeList0,
MailList2 : CodeList2,
MailList3 : CodeList3,
MailList4 : CodeList4
}
Now if you want to add MailList1 (which has the same value as MailList0) to the dictionary, check if MailList1 already is a list. 现在,如果要将MailList1(具有与MailList0相同的值)添加到字典中,请检查MailList1是否已经是列表。 if it is not a list make it into a list and then append the new value.
如果不是列表,则将其放入列表,然后附加新值。
if(MailList1 in Mail_Dict):
if (isinstance(Mail_Dict[MailList1],list)==False):
Mail_Dict[MailList1] = [Mail_Dict[MailList1]
Mail_Dict[MailList1].append(codeList1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.