jtsmith1287
jtsmith1287

Reputation: 1149

Python 2.7 - String Substitution using multiple dictionaries

I am mostly self taught, so I'm having a hard time looking up the answer - I think because I don't know what it's called.

Basically I need to use the "%(dict_key)s" %(dict) syntax but using multiple dictionaries. I have no idea how to do this. A quick rough example would be:

dict1 = {"foo": "bar"}
dict2 = {"car": "vroom"}

print "Value 1 is %(foo)s and value 2 is %(car)s" %(dict1, dict2)

That example doesn't work, obviously, but that's what I need. How do I do this? I'm looking for the simplest solution.

Upvotes: 1

Views: 763

Answers (1)

falsetru
falsetru

Reputation: 369134

You can use dict(dict1, **dict2):

>>> dict1 = {"foo": "bar"}
>>> dict2 = {"car": "vroom"}

>>> dict(dict1, **dict2)
{'car': 'vroom', 'foo': 'bar'}

>>> print "Value 1 is %(foo)s and value 2 is %(car)s" % dict(dict1, **dict2)
Value 1 is bar and value 2 is vroom

Upvotes: 3

Related Questions