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 = """ # from www .java2 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 # ww w . jav  a  2s  . co  m
print( vars() )

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

Result

Related Topic