Python Format with Dictionary Object

Kontext Kontext 0 562 0.52 index 7/15/2022

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

python

Join the Discussion

View or add your thoughts below

Comments