简体   繁体   中英

Insert values of dict1 into dict2 but in a specific place in dict2

I have 2 dictionaries and I want to insert the values of dict1 into dict2 but in a specific place in dict2, ie:

dict1

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

dict2

{
 'apple': '<div class="apple"></div>',
 'orange': '<div class="orange"></div>',
 'banana': '<div class="banana"></div>'
 }

I want to insert the values of dict1 into dict2 inside the 'class=' variable so it becomes

Desired

{
 'apple': '<div class="apple hard tasty"></div>',
 'orange': '<div class="orange soft tasty"></div>',
 'banana': '<div class="banana soft very-tasty"></div>'
 }

Can you help me with this? I may have to import re or use regex. I've been using dict comprehensions for the iterations

There is no need of regex or any additional imports. Use str.replace instead:

dict1 = {
       'apple': 'hard tasty', 'orange': 'soft tasty',   
       'banana': 'soft very-tasty'
        }
dict2 = {
       'apple': '<div class="apple"></div>',
       'orange': '<div class="orange"></div>',
       'banana': '<div class="banana"></div>'
        }

d = {k: v.replace(k, k+' '+dict1[k]) for k, v in dict2.items()}
print(d)

# {'apple': '<div class="apple hard tasty"></div>', 
#  'orange': '<div class="orange soft tasty"></div>', 
#  'banana': '<div class="banana soft very-tasty"></div>'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM