3

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)

4 Answers 4

14

Use keyword expansion on the dictionary:

"{a};{b};{c};{d}".format(**myDictionary)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
"""%(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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.