Reputation: 2598
Is there a way to write this line of code in a better way :
"""{a};{b};{c};{d}""".format(a = myDictionary[a], b = myDictionary[b], c = myDictionary[c], d = myDictionary[d])
something like this ?
"""{a};{b};{c};{d}""".format(myDictionary)
Upvotes: 3
Views: 686
Reputation: 1015
Is this what you looking for?
di = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3'
}
print "value of key3 is: %(key3)s" % di
value of key3 is: value3
Upvotes: 0
Reputation: 110208
"""%(a)s;%(b)s;%(c)s;%(d)s""" % myDictionary
Despite a lot of controversy and pushes, the traditional string formatting operator "%" has no motives (nor signs) to go away,a s a lot of things are simpler with it.
Upvotes: 0
Reputation: 177481
format
can dereference its parameters:
>>> D=dict(a=1,b=2,c=3,d=4)
>>> '{0[a]};{0[b]};{0[c]};{0[d]}'.format(D)
'1;2;3;4'
A similar syntax can be used on classes:
>>> class C:
... a=1
... b=2
... c=3
... d=4
...
>>> '{0.a};{0.b};{0.c};{0.d}'.format(C)
'1;2;3;4'
See the Format Specification Mini-Language.
Upvotes: 1
Reputation: 212835
Use keyword expansion on the dictionary:
"{a};{b};{c};{d}".format(**myDictionary)
Upvotes: 14