获取2个字典中(几乎)匹配键的值并将其加入

时间:2018-08-03 14:22:09

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

所以我想获取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>"
}

我希望运行第一行代码可以工作,但是我不认为语法正确。

1 个答案:

答案 0 :(得分:2)

将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)