Methods and Functions

Python String format_map()

Python format_map() function is somewhat similar in functionality to the Python format() function. We use Python format_map() function when we want to map each key with its value and then the mapping is a dict subclass. Here, mapping can be viewed in the form of {key: value} i.e. in a Dictionary form. This article focuses more on the applicability of the Python format_map() string method along with its examples.

Python format_map() function

Definition

  • The Python format_map() string function returns a formatted version of the string using substitutions based on the mapping specified. The substitution arguments are included in the string and are denoted by curly braces {}.
  • Python format_map() returns a new string by concatenating the values in the user-supplied dict within the defined places. This approach uses the placeholder ({}) formatting style.
  • This format_map() function is used to returns a dictionary key’s value.

Python format_map() Syntax

Python format_map() follows the below syntax:

                    

string.format_map(mapping)

format_map() Parameters

The format_map() accepts a single argument:

  • mapping (dictionary) – A dictionary with key-value pair required for mapping

Return value from format_map()

The Python format_map() formats the given string and returns the key’s values of the input dictionary.

Example 1: How format_map works?

Example

                    

# Python program to illustrate format_map()
# mapping dictionary
stud_marks = {'x':'Phillip', 'y':89, 'z':'Maths'}
# format string
txt = '{x} scored {y} marks in {z}'
print(txt.format_map(stud_marks))
print('')

print('My {x} is {y} USD'.format_map({'x':'Salary', 'y':4500}))

Output

                    

Phillip scored 89 marks in Maths

My Salary is 4500 USD

Explanation

We have considered stud_marks as a mapping dictionary. Then we have declared a format string txt having the keys of the mapping dictionary under the format substitution (curly brackets). Now, we can substitute all occurrences of {x}, {y} and {z} with Phillip, 89 and Maths using the format_map() function.

Example 2: KeyError in format_map()

What if we add another extra format that does not exist on the mapping dictionary? Or what if we miss keys in the mapping dictionary? In such cases, the format_map() function throws a KeyError exception which displays the key that is extra added or missed in the mapping dictionary.

Example 1

                    

details = {'name':'Emily', 'lang1':'Java'}
# added extra format that does not exist in mapping dict
txt = '{name} loves {lang1} and {lang2}'
print(txt.format_map(details))

Output

                    

Traceback (most recent call last):
File "", line 4, in 
KeyError: 'lang2'

Example 2

                    

# contains 1 less key
details = {'name':'Emily'}
txt = '{name} loves {lang1}'
print(txt.format_map(details))

Output

                    

Traceback (most recent call last):
File "", line 4, in 
KeyError: 'lang1'

Example 3: How does format_map() work with dict subclass?

The format_map(mapping) function is more adaptable than format(**mapping) because it allows for missing keys.

Example

                    

# Python program to illustrate format_map()
class Coordinates(dict):
    def __missing__(self, key):
      return key


print('({x}, {y}, {z})'.format_map(Coordinates(x = '5')))

print('({x}, {y}, {z})'.format_map(Coordinates(y = '10')))

print('({x}, {y}, {z})'.format_map(Coordinates(x = '5', y = '10', z = '15')))

Output

                    

(5, y, z)
(x, 10, z)
(5, 10, 15)

Practical Applications of format_map()

Any practical application can take advantage of the format map() method.

Example

                    

# Program 1
def chk_msg(n):
    # input stored in variable details.
    details = {'name':'Alex', 'msg':n}
    # use of format_map() function
    print('{name} has {msg} new messages'.format_map(details))

chk_msg(25)
print('')

# Program 2
detail = { 'name':['Sean', 'David'],
               'profession':['Architect', 'Businessman'],
               'age':[34, 29] }

print('{name[0]} is an {profession[0]} and he'
      ' is {age[0]} years old'.format_map(detail))

print('{name[1]} is a {profession[1]} and he'
      ' is {age[1]} years old'.format_map(detail))

Output

                    

Alex has 25 new messages

Sean is an Architect and he is 34 years old
David is a Businessman and he is 29 years old

Difference between format_map() and format()

  • The Python format() function performs an indirect substitution utilizing the method parameters by first generating a mapping dictionary and then conducting the substitution.
  • In the instance of Python String format_map(), the substitution is performed directly using a mapping dictionary.
  • The format_map() is significantly faster than format() because it does not create a new dictionary ().
  • Also format map(), unlike format(), can use a dictionary subclass for mapping.
Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.