Python - Dictionary-Based Formatting Expressions

Introduction

String formatting also allows conversion targets on the left to refer to the keys in a dictionary coded on the right.

Demo

print( '%(qty)d more %(food)s' % {'qty': 1, 'food': 'test'} )

Result

Here, the (qty) and (food) in the format string on the left refer to keys in the dictionary literal on the right.

The code would get their associated values.

The following code shows how to use this feature to build a template.

Demo

# Template with substitution targets 
reply = """ # www .j  a  v  a2  s.  c o m
Greetings... 
Hello %(name)s! 
Your age is %(age)s 
 """ 
values = {'name': 'Bob', 'age': 40}       # Build up values to substitute 
print(reply % values)                     # Perform substitutions

Result

The vars built-in function returns a dictionary containing all the variables that exist in the place it is called:

Demo

food = 'test' 
qty = 10 # from  ww w  .  j  ava2s  .c  om
print( vars() )

print( '%(qty)d more %(food)s' % vars() )         # Variables are keys in vars()

Result

Related Topic