【发布时间】:2022-01-20 16:26:59
【问题描述】:
如果我有以下两个字典和列表:
locator = ['LOCATOR1']
dict1 = {
'LOCATOR1': ['18d42734-c8c6-4409-81cf-315cdc5f02c4'],
'LOCATOR2': ['8ddec8ba-4418-4cef-8cd9-72808f615502']
}
dict2 = {
'LOCATOR3': ['0c4543be-38e3-4647-bd35-b40690429233'],
}
我希望实现的是使用我的列表'locator'从dict1中的'locator'中找到匹配的键及其值并将其复制到dict 2,这样我就有了这样的东西:
dict2 = {
'LOCATOR3': ['0c4543be-38e3-4647-bd35-b40690429233'],
'LOCATOR1': ['18d42734-c8c6-4409-81cf-315cdc5f02c4']
}
然后我可以从 dict1 中删除 LOCATOR1。
【问题讨论】:
-
for key in locator: dict2[key] = dict1.pop(key). -
工作愉快,谢谢。
-
不客气!
-
请记住,如果在
dict1中找不到密钥,@Guimute 的建议将失败并出现 KeyError。
标签: python python-3.x dictionary