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

大城市里の小女人 提交于 2019-12-11 15:46:53

问题


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


回答1:


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>'}


来源:https://stackoverflow.com/questions/50906279/insert-values-of-dict1-into-dict2-but-in-a-specific-place-in-dict2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!