【问题标题】:Python copy specific key/value from one dictionary to anotherPython将特定键/值从一个字典复制到另一个
【发布时间】: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


【解决方案1】:

你可以在 dict2 上使用 update 函数,它会从 dict1 中弹出键:

dict2.update((k,dict1.pop(k)) for k in locator if k in dict1)

{'LOCATOR3': ['0c4543be-38e3-4647-bd35-b40690429233'], 
 'LOCATOR1': ['18d42734-c8c6-4409-81cf-315cdc5f02c4']}

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2022-07-10
    相关资源
    最近更新 更多