Python String format_map() Method
By Lenin Mishra
If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.
Difference between format()
and format_map()
in Python
The format_map()
method is similar to format()
method in Python., except that it only accepts a dictionary as input.
Learn more about Python String format() method.
Syntax of format_map()
method
string.format_map(mapping)
mapping: The Input dictionary
Example 1
Code
s = '{name} lives in {country}'
my_dict = {'name': 'Pylenin', 'country': 'India'}
# Using format_map() method
print(s.format_map(my_dict))
# Using format() method
print(s.format(**my_dict))
Output
Pylenin lives in India
Pylenin lives in India
Example 2 - If mapping has more keys
If mapping dictionary has more keys, then only the necessary keys are used for string formatting.
Code
s = '{name} lives in {country}'
my_dict = {'name': 'Pylenin',
'country': 'India',
'language': 'Python'}
# Using format_map() method
print(s.format_map(my_dict))
# Using format() method
print(s.format(**my_dict))
Output
Pylenin lives in India
Pylenin lives in India
Example 3 - If mapping has missing keys
If mapping dictionary has missing keys, both format()
and format_map()
will throw a KeyError
.
Code
s = '{name} lives in {country}'
my_dict = {'name': 'Pylenin',
'country': 'India',
'language': 'Python'}
# Using format_map() method
print(s.format_map(my_dict))
# Using format() method
print(s.format(**my_dict))
Output
# format_map()
KeyError: 'country'
# format()
KeyError: 'country'
Advantage of format_map() over format()
With the format_map()
method, you can avoid such KeyError
issues by working with a dict subclass.
Let’s look at the below example.
Code
class PyleninDict(dict):
def __missing__(self, key):
return '{}'
s = '{name} is born in {country}'
my_dict = PyleninDict(name='Pylenin')
print(s.format_map(my_dict))
Output
Pylenin is born in {}
As you can see, we didn’t receive a KeyError
anymore. The __missing__
function was called and format_map()
was able to handle the missing key.
The above doesn’t work for format()
method
Code
class PyleninDict(dict):
def __missing__(self, key):
return '{}'
s = '{name} is born in {country}'
my_dict = PyleninDict(name='Pylenin')
# Using format() instead of format_map()
print(s.format(**my_dict))
Output
KeyError: 'country'
Check out other commonly used Python string methods.
Related Articles
- How to create a string in Python?
- How to access characters in a Python string?
- How to replace characters in a string in Python?
- How to concatenate strings in Python?
- How to iterate through a string in Python?
- Check if a Substring is Present in a Given String in Python
- Escape sequences in Python String
- Python String Formatting - The Definitive Guide