Python string format with dictionary

As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping) (Python 3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

What this means is that you can use for example a defaultdict that would set (and return) a default value for keys that are missing:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

Even if the mapping provided is a dict, not a subclass, this would probably still be slightly faster.

The difference is not big though, given

>>> d = dict(foo='x', bar='y', baz='z')

then

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

is about 10 ns (2 %) faster than

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and


Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

Starting from 3.6 you can use the interpolated strings too:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we will discuss how to format a string using a dictionary in Python.

    Method 1: By using str.format() function

    The str.format() function is used to format a specified string using a dictionary.

    Syntax: str .format(value)

    Parameters: This function accepts a parameter which is illustrated below:

    • value: This is the specified value that can be an integer, floating-point numeric constant, string, characters, or even variables.

    Return values: This function returns a formatted string using a dictionary.

    Example: Formatting a string using a dictionary

    Python3

    value = {"Company": "GeeksforGeeks"

             "Department": "Computer Science"}

    print("{Company} is a {Department} Portal.".format(**value))

    Output:

    GeeksforGeeks is a Computer Science Portal.

    Method 2: Using % operator

    % – Formatting is a feature provided by Python which can be accessed with a % operator. This is similar to printf style function in C. In this approach, a dictionary is used in which you need to provide the key in the parentheses between the % and the conversion character.  

    Example: Formatting a string using a dictionary

    Python3

    print('%(Company)s is a %(Department)s Portal.'  

              %{'Company': "GFG", 'Department': "CS"})

    Output:

    GFG is a CS Portal.

    Use format() function to format dictionary print in Python. Its in-built String function is used for the purpose of formatting strings according to the position.

    Python Dictionary can also be passed to format() function as a value to be formatted.

    "{key}".format(**dict)

    The simple example code key is passed to the {} and the format() function is used to replace the key by its value, respectively. Thus, Python “**” operator is used to unpack the dictionary.

    dict1 = {"a": 100, "b": 200, "c": 300}
    
    res = "{a} {b}".format(**dict1)
    print(res)
    

    Output:

    Python string format with dictionary

    Python format dictionary pretty

    import json
    
    d = {'a': 2, 'b': {'x': 3, 'y': {'t1': 4, 't2': 5}}}
    res = json.dumps(d, sort_keys=True, indent=4)
    
    print(res)
    

    Output:

    {
        "a": 2,
        "b": {
            "x": 3,
            "y": {
                "t1": 4,
                "t2": 5
            }
        }
    }
    

    Do comment if you have any doubts or suggestions on this Python dictionary topic.

    Note: IDE: PyCharm 2021.3 (Community Edition)

    Windows 10

    Python 3.10.1

    All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

    Python string format with dictionary

    Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

    How do you format a string in a dictionary Python?

    Method 1: By using str..
    Syntax: str .format(value).
    Parameters: This function accepts a parameter which is illustrated below:.
    Return values: This function returns a formatted string using a dictionary..

    What is %d and %s in Python?

    %s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))

    What is the point of .format in Python?

    Format Function in Python (str. format()) is technique of the string category permits you to try and do variable substitutions and data formatting. It enables you to concatenate parts of a string at desired intervals through point data format.

    How do I print a formatted dictionary in Python?

    Use format() function to format dictionary print in Python. Its in-built String function is used for the purpose of formatting strings according to the position. Python Dictionary can also be passed to format() function as a value to be formatted.