【问题标题】:Get values for (almost) matching keys in 2 dictionaries and join them获取 2 个字典中(几乎)匹配键的值并加入它们
【发布时间】:2019-01-11 11:16:23
【问题描述】:

所以我想在 2 个字典中获取(几乎)匹配键的值并加入它们。我试过了:

dict3 = {key:dict1[key].strip() for key in dict2.keys() if key.partition('__')[0] in dict1}

...但我没有得到任何结果,因为它没有找到任何匹配项,我的字典在下面,我知道我很接近但我错过了一些东西:

dict1:

{
    "h1__display-3": "",
    "h1__display-3_text-white_text-center": "",
    "h1__mt-4": "",
    "h1__mt-5": "",
    "h1__mt-5_kakabum": "",
    "h1__my-4": "",
    "h2__card-title": "",
    "h2__mt-4": "",
    "h2__my-4": ""
}

dict2:

{
    "h1": "<h1>[]</h1>",
    "h2": "<h2>[]</h2>"
}

期望的结果:

{
    "h1": "<h1>[]</h1>",
    "h1__display-3": "<h1>[]</h1>",
    "h1__display-3_text-white_text-center": "<h1>[]</h1>",
    "h1__mt-4": "<h1>[]</h1>",
    "h1__mt-5": "<h1>[]</h1>",
    "h1__mt-5_kakabum": "<h1>[]</h1>",
    "h1__my-4": "<h1>[]</h1>",
    "h2": "<h2>[]</h2>",
    "h2__card-title": "<h2>[]</h2>",
    "h2__mt-4": "<h2>[]</h2>",
    "h2__my-4": "<h2>[]</h2>"
}

我希望运行第一行代码会起作用,但我认为我的语法不正确。

【问题讨论】:

    标签: python string python-3.x dictionary dictionary-comprehension


    【解决方案1】:

    将 dict 结构分解成一个普通的循环会更容易理解。我们想要

    res = {}
    for k in dict1:
        key = k.split('__')[0]
        if key in dict2:
            res[k] = dict2[key]
    

    相当于

    res = {k: dict2[k.split('__')[0]] for k in dict1 if k.split('__')[0] in dict2}
    

    这不会添加 h1h2 作为键,但使用

    可以轻松完成
    res.update(dict2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 2021-12-27
      • 2022-08-03
      • 1970-01-01
      • 2022-01-26
      • 2021-01-10
      • 1970-01-01
      相关资源
      最近更新 更多