问题
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