format_map()
methodformat_map()
is a built-in method in Python that is used to replace all keys in the string with its values.
The format_map()
method returns a new string by concatenating the values in the dictionary
provided within the specified positions. format_map()
does not create a new dictionary object; instead, it works by getting dictionary
values as arguments
.
The syntax of the format_map()
method is shown below.
string.format_map(mapping)
From the syntax above, the format_map()
method only takes one required argument. The argument is a dictionary
value used for mapping.
format_map()
versus format()
The format_map()
method is very similar to the format()
method in Python. The difference is that the format()
method needs to unpack the dictionary while passing arguments.
Additionally, the format()
method creates a new dictionary while the format_map()
method does not. Thus, the format_map()
method is slightly faster than the format()
method.
Below are sample codes that use the format_map()
method.
sample_string = {'firstname':'Jane','lastname':'Doe'}print('{firstname} {lastname}'.format_map(sample_string))
Jane Doe
client_details = { 'name':['Jax', 'Jim'],'occupation':['Lawyer', 'Teacher'],'age':[35, 30] }print('{name[0]} is a {occupation[0]} and'' he is {age[0]} years old.'.format_map(client_details))print('{name[1]} is a {occupation[1]} and'' he is {age[1]} years old.'.format_map(client_details))
Jax is a Lawyer and he is 35 years old.
Jim is a Teacher and he is 30 years old.