Reputation: 302
So I want to get values for (almost) matching keys in 2 dictionaries and join them. I tried:
dict3 = {key:dict1[key].strip() for key in dict2.keys() if key.partition('__')[0] in dict1}
...but I dont get any results because it's not finding any matches, my dicts are below, I know i'm close but I'm missing something:
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>"
}
Desired outcome:
{
"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>"
}
I was hoping that running the first line of code would work, but I dont think i have the syntax right.
Upvotes: 1
Views: 39
Reputation: 61032
Breaking the dict construction out into an ordinary loop mkaes it a little easier to follow. We want
res = {}
for k in dict1:
key = k.split('__')[0]
if key in dict2:
res[k] = dict2[key]
which is equivalent to
res = {k: dict2[k.split('__')[0]] for k in dict1 if k.split('__')[0] in dict2}
This doesn't add h1
and h2
as keys, but that's easily accomplished with
res.update(dict2)
Upvotes: 2