Python Format with Dictionary Object

visibility 68 event 2022-07-15 access_time 5 months ago language English
more_vert

Python format is commonly used to replace placeholders with variables. The following is an typical example:

a = "100"
b = "200"
string = "a={a}, b={b}".format(a=a, b=b)
print(string)

It outputs a string with this value - "a=100, b=200". In some scenarios, it is very convenient to use a dictionary to format string. This can be done using '**' operator in Python. In other programming languages, this is called splat or spread operator.

Code snippets

dict = {'a': "100", 'b': "100"}
string = "a={a}, b={b}".format(**dict)
print(string)
The output is the same as the above:
a=100, b=200
copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts