从另一个字典更新多值字典中的值

2024-04-20 06:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个字典,我正在寻找一种方法来更新多值字典IP\u列表中的值,方法是检查dictionary ID\u列表中的值。基本上,我需要用id\u列表中的id值替换IP\u列表中的电子邮件字符串。你知道吗

IP_list={'ip1': ['email1', 'string1'], 'ip2': ['email2', 'string2'],'ip3': ['email2', 'string3']}
ID_list={'email1': 'id1', 'email2': 'id2', 'email3': 'id3'}

预期输出:
{'ip1': ['id1', 'string1'], 'ip2': ['id2', 'string2'],'ip3': ['id2', 'string3']}
或者可以在特定键值的末尾添加ID值,如:
{'ip1': ['email1','string1','id1'], 'ip2': ['email2','string2','id2'],'ip3': ['email2','string3','id2']}

有人能帮忙吗?你知道吗

谢谢 J

你知道吗编辑:我试过了Roman建议的解决方案它可以在Python2.7.5上工作,没有问题,但是我很难让它在Python2.6.6上工作

@Roman,IP_列表由MSSQL db创建:

for row in results:
      IP_list[row.IP_address]= row.email, row.description

print IP_list将给出: 在Python 2.7.5的开发环境中,我将得到:

{'IP': ('email1', 'description "info"'),'IP2': ('email2', 'description')}

在使用python2.6.6的生产系统上,我将获得一些unicode值

{'IP': (u'email1', u'description "info"'),'IP2': (u'email2', u'description')}

所以我将unicode值转换为ascii,所以应该没有问题。你知道吗

ID\列表是从XML创建的,输出在两个环境中是相同的:

{'email1': 'id1', 'email2': 'id2', 'email3': 'id3'}

当我在Python2.7.5上运行这个脚本时,它工作得很好,但是在2.6.6上它会给我这个错误

val[0] = ID_list.get(val[0], val[0])
TypeError: 'tuple' object does not support item assignment

Tags: ipid列表descriptionlistrowid2id1
1条回答
网友
1楼 · 发布于 2024-04-20 06:27:26

比如:

for val in IP_list.itervalues():
    val[0] = ID_list.get(val[0], val[0])

如果来自IP_list的电子邮件在ID_list中丢失,则不会更改。你知道吗

现在IP地址列表如下所示:

{'ip2': ['id2', 'string2'], 'ip3': ['id2', 'string3'], 'ip1': ['id1', 'string1']}

相关问题 更多 >