Skip to content Skip to sidebar Skip to footer

Update Value Of Dict2 From Dict1 But In A Specific Place In Dict2

Having 2 dictionaries I want to insert the values of dict1 into dict2 but in a specific place in dict2 I asked a similar question here which was solved in this way: d = {k: v.repla

Solution 1:

You can use re.sub:

importred= {'apple': 'hard tasty', 'orange': 'soft tasty', 'banana': 'soft very-tasty'}
d1 = {'apple': '<div class="a"></div>', 'orange': '<div class="o"></div>', 'banana': '<div class="b a"></div>'}
new_d = {a:re.sub('(?<=class\=")[\w+\s\-\_]+(?=")', lambda x:x.group()+' '+d[a], b) for a, b in d1.items()}

Output:

{'apple': '<divclass="a hard tasty"></div>', 'orange': '<divclass="o soft tasty"></div>', 'banana': '<divclass="b a soft very-tasty"></div>'}

Solution 2:

In the same way as the answer to your first question, here is my solution using re.sub:

import re

dict1 = {'apple': 'hard tasty', 'orange': 'soft tasty', 'banana': 'soft very-tasty'}

dict2 = {'apple': '<div class="a"></div>',
         'orange': '<div class="o"></div>',
         'banana': '<div class="b a"></div>'
        }

d = {k: re.sub(r'class="([\w\- ]+)"', r'class="\1 ' + dict1[k] + '"', v) for k,v in dict2.items()}

print(d)
# {#  'apple': '<div class="a hard tasty"></div>',#  'orange': '<div class="o soft tasty"></div>',#  'banana': '<div class="b a soft very-tasty"></div>'#  }

Solution 3:

first = {
'apple': 'hard tasty', 'orange': 'soft tasty', 'banana': 'soft very-tasty'
}

second = {
'apple': '<div class="a"></div>',
'orange': '<div class="o"></div>',
'banana': '<div class="b a"></div>'
}

for k, v in second.items():
    lst = v.split("\"", 2)
    second[k] = "{} {}\"{}".format("\"".join(lst[:-1]), first[k], lst[-1])

Output

 {
 'apple': '<divclass="a hard tasty"></div>',
 'orange': '<divclass="o soft tasty"></div>',
 'banana': '<divclass="b a soft very-tasty"></div>'
 }

Post a Comment for "Update Value Of Dict2 From Dict1 But In A Specific Place In Dict2"