Python - String Method - format_map() Tutorial
This method is similar to format(**mapping), the only difference is format_map() will create a new dictionary during method call, while format(**mapping) just copy the dictionary.
Let see the difference between the both method.
example for format(**mapping)-
point = {'x':'Python','y':'Fresherbell'}
print('Hello {x}, Hello {y}'.format(**point))
print('Hello {x}, Hello {y} {z}'.format(**point))
Output-
Hello Python, Hello Fresherbell
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6176/172717043.py in <module>
1 point = {'x':'Python','y':'Fresherbell'}
2 print('Hello {x}, Hello {y}'.format(**point))
----> 3 print('Hello {x}, Hello {y} {z}'.format(**point))
KeyError: 'z'
format(**mapping) is not good at handling missing key.
example for format_map()-
class Default(dict):
def __missing__(self, key):
return key
point = {'x':['Python','World'],'y':'Fresherbell'}
print('Hello {x[1]}, Hello {y}'.format_map(point))
print('Hello {x[1]}, Hello {y} {z}'.format_map(Default(point)))
Output-
Hello World, Hello Fresherbell
Hello World, Hello Fresherbell z
format_map() is slightly fast and good in handling missing key with the help of class.