The format_map() function in python makes a new dictionary which is used to return a dictionary key’s value. Here str is the key of the input dictionary and mapping is a variable in which the input dictionary is stored. This function replaces all keys in the string with the value.
str.format_map(mapping) #where mapping is the variable
The format_map() takes a single argument mapping(dictionary).
Parameter | Description | Required / Optional |
---|---|---|
mapping | mapping dictionary | Required |
This method returns a formatted version of the string using a map-based substitution, using curly brackets {}.
Input | Return Value |
---|---|
mapping | formatted string |
point = {'a':1,'b':-2}
print('{a} {b}'.format_map(point))
point = {'a':1,'b':-2, 'c': 0}
print('{a} {b} {c}'.format_map(point))
Output:
1 -2 1 -2 0
class Coordinate(dict):
def __missing__(self, key):
return key
print('({a}, {b})'.format_map(Coordinate(a='1')))
print('({a}, {b})'.format_map(Coordinate(b='2')))
print('({a}, {b})'.format_map(Coordinate(a='1', b='2')))
Output:
(1, b) (a, 2) (1, 2)