Python | format function ()

| | | | | |

str.format () is one of the string formatting methods in Python3 that allows multiple replacements and formatting of values. This method allows us to concatenate elements in a string through positional formatting.

Using a single formatter:

Formatters work by placing one or more placeholders and placeholders defined by a pair of curly braces { }, to a string and calling str.format (). The value we want to put in placeholders and concatenate with the string passed as parameters to the formatting function.

Syntax: {} .format (value)

Parameters:
(value): Can be an integer, floating point numeric constant, string, characters or even variables.

Returntype: Returns a formatted string with the value passed as parameter in the placeholder position.

Code # 1 : Simple format demo ().

# Python3 demo program
# str.format () method


# using the format parameter in a simple string

print ( "{}, A computer science portal for geeks. "

. format ( " Python.Engineering " ))


# using the format option for
# the value is stored in a variable

str = " This article is written in {} "

print ( str . format ( "Python" ))


# string formatting using a numeric constant

print ( " Hello, I am {} years old! " . format ( 18 ))

Output:

 GeeksforGeeks, A computer science portal for geeks. This article is written in Python Hello, I am 18 years old! 

Using multiple formatters:

Multiple pairs of curly braces can be used when formatting a string. For example, if your sentence requires a different substitution of variables, you can do this by adding a second pair of curly braces and passing the second value to the method. Python will replace placeholders with values ‚Äã‚Äãin order.

Syntax: {} {} .format (value1, value2)

Parameters:
(value1, value2): Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values ‚Äã‚Äãpassed as parameters in format () method must be equal to the number of placeholders created in the string.

Errors and Exceptions:
IndexError: Occurs when string has an extra placeholder and we didn’t pass any value for it in the format () method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3 .... to acces the values ‚Äã‚Äãpassed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError.

Code # 2:

# Python program showing index error


# There are four placeholders, but
# only three values ‚Äã‚Äãpassed


# parameters in the formatting function.

my_string = "{}, is a {} {} science portal for {}"

print (my_string. format ( " Python.Engineering " , " computer " , "geeks" ))

Output:

 Traceback (most recent call last): File "/ home / 949ca7b5b7e26575871639f03193d1b3.py ", line 2, in print (my_string.format (" Python.Engineering "," computer "," geeks ")) IndexError: tuple index out of range 

Code # 3: Formatters with multiple placeholders.

# Python program that uses multiple places
# holders to demonstrate the str.format () method


# Multiple placeholders in a function format ()

my_string = "{}, is a {} science portal for {}"

print (my_string. format ( "GeeksforGeeks" , "computer" , " geeks " ))


# different data types can be used for formatting

print ( "Hi! My name is {} and I am {} years old "

. format ( "User" , 19 ))


# Values ‚Äã‚Äãpassed as parameters
# are replaced in the order they are entered

print ( "This is {} {} {} {}"

. format ( "one" , "two" , "three" , " four " ))

Output:

 GeeksforGeeks, is a computer science portal for geeks Hi! My name is User and I am 19 years old This is one two three four 

Formatters with positioning and keyword arguments:

When placeholders are {} are empty, Python will replace the values ‚Äã‚Äãpassed through str.format () in order.

The values ‚Äã‚Äãthat exist in the str.format () method are essentially tuple data types , and each distinct value contained in a tuple can be called by its index number, which starts at index number 0. These index numbers can be passed in curly braces that serve as placeholders in the original string.

Syntax: {0} {1} .format (positional_argument, keyword_argument)

Parameters: (positional_argument, keyword_argument)

Positional_argument can be integers, floating point numeric constants, strings, characters and even variables.
Keyword_argument is essentially a variable storing some value, which is passed as parameter.

Code # 4:

# To demonstrate the use of formatters
# with positional keyword arguments.


# Positional arguments
# in order

print ( "{0} love {1} !!" . format ( " Python.Engineering " ,

"Geeks" ))


# Swap the number and index with
# placeholder options

print ( "{1} love {0} !!" . format ( "GeeksforGeeks" ,

"Geeks" ))

print ( "Every {} should know the use of {} {} programming and {}"

. format ( "programmer" , "Open" , "Source" , "Operating Systems" ))


# Use index numbers
# values ‚Äã‚Äãto reorder
# they appear on the line

print ( "Every {3} should know the use of {2} {1} programming and {0}"

. format ( "programmer" , "Open" , " Source " , " Operating Systems " ))


# Keyword arguments are named
# by keyword name

print ( "{gfg} is a {0} science portal for {1}"

. format ( " computer " , " geeks " , gfg = "GeeksforGeeks" ))

Output:

 Python.Engineering love Geeks !! Geeks love Python.Engineering !! Every programmer should know the use of Open Source programming and Operating Systems Every Operating Systems should know the use of Source Open programming and programmer Python.Engineering is a computer science portal for geeks 

Type Specification:

Additional parameters can be included in curly braces in our syntax. Use the format code syntax {field_name: transform} , where field_name specifies the ordinal number of the argument to the str.format () method, and the transform refers to the data type conversion code.

s - strings
d - decimal integers (base-10)
f - floating point display
c - character
b - binary
o - octal
x - hexadecimal with lowercase letters after 9
X - hexadecimal with uppercase letters after 9
e - exponent notation

Syntax:
String {field_name: conversion} Example.format (value)

Errors and Exceptions:
ValueError: Error occurs during type conversion in this method.

Code # 5:

# Show ValueError while
# make forced pr Type conversions


# When explicitly converting a floating point number
Number of values ‚Äã‚Äãin base-10 decimal with "d"
# type conversion we encounter Value-Error.

print ( "The temperature today is {0: d} degrees outside! "

. format ( 35.567 ))


# Write this instead to avoid erroneous values ‚Äã‚Äã
& # 39; & # 39; & # 39; print (& quot; The temperature today is {0: .0f} degrees outside! & Quot;

. format (35,567)) & # 39; & # 39; "

Output:

 Traceback (most recent call last): File "/home/9daca03d1c7a94e7fb5fb326dcb6d242.py", line 5, in print ("The temperature today is {0: d} degrees outside! ". format (35.567)) ValueError: Unknown format code’ d’ for object of type ’float’ 

Code # 6:

# Convert base-10 decimal integers
# to floating point numeric constants

print ( "This site is { 0: f}% securely {1} !! " .

format ( 100 , "encrypted" ))


# To limit accuracy

print ( "My average of this {0} was {1: .2f}%"

. format ( " semester " , 78.234876 ))


# No decimal places

print ( "My average of this {0} was {1: .0f}%"

. format ( "semester" , 78.234876 ))


# Convert an integer to its binary or
# with various other converted bases.

print ( " The {0} of 100 is {1: b} "

. format ( "binary" , 100 ))

print ( "The {0} of 100 is {1: o} "

. format ( "octal" , 100 ))

Exit:

 This site is 100.000000% securely encrypted !! My average of this semester was 78.23% My average of this semester was 78% The binary of 100 is 1100100 The octal of 100 is 144 

Substitutions or generating spaces :

Code # 7:

By default, lines are aligned to the left of the field, and numbers — on the right. We can change this by placing the alignment code right after the colon.

  & lt; : left-align text in the field  ^ : center text in the field  & gt; : right-align text in the field 

# To demonstrate distance when
# strings are passed as parameters

print ( "{0: 4}, is the computer science portal for {1: 8}!"

. format ( "Python.Engineering " , " geeks " ))


# To sell monstrate the interval when numeric
# constants are passed as parameters.

print ( " It is {0: 5} degrees outside! "

. format ( 40 ) )


# To demonstrate both string and numeric
# constants passed as parameters

print ( "{0: 4} was founded in {1:16}!"

. format ( "GeeksforGeeks" , 2009 ))


# To propose tune space alignment

print ( "{ 0: ^ 16} was founded in {1: & lt; 4}! "

. format ( "GeeksforGeeks" , 2009 ))

print ( "{: * ^ 20s} " . format ( "Geeks" ))

Output:

 GeeksforGeeks, is the computer science portal for geeks! It is 40 degrees outside! Python.Engineering was founded in 2009! Python.Engineering was founded in 2009! ******* Geeks ******** 

Applications:

Formatters are commonly used to organize data. Formatters can be seen in their best light when they are used to visually organize large amounts of data. If we’re showing databases to users, using formatters to increase the field size and change the alignment can make the output more readable.

Code # 8: To Demonstrate Big Data Organization

# which prints i, i ^ 2, i ^ 3,
# i ^ 4 in the given range


# The function outputs values ‚Äã‚Äã
# unorganized

def unorganized (a, b):

for i in range (a, b):

print (i, i * * 2 , i * * 3 , i * * 4 )


# The function prints an organized set of values ‚Äã‚Äã

def organized (a, b):

for i in range (a, b ):

# Using formatters to give 6

# spaces for each set of values ‚Äã‚Äã

print ( "{: 6d} {: 6d} {: 6d} {: 6d} "

. format (i, i * * 2 , i * * 3 , i * * 4 ))


Driver code

n1 = int ( input ( " Enter lower range: - " ))

n2 = int ( input ( "Enter upper range: -" ))

print ( "--- --- Before Using Formatters ------- " )


# Calling a function without formatters
unorganized (n1, n2)

print ()

print ( "------- After Using Formatters ---------" )

print ()


# Call a function containing
# formatters for organizing data
organized (n1, n2)

Output:

 Enter lower range: - 3 Enter upper range: - 10 ------ Before Using Formatters ------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 ------- After Using Formatters --------- 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561 

Python | format function () Counters: Questions

Python | format function () exp: Questions

exp

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

5 answers

Carl Meyer By Carl Meyer

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place.

>>> x = {"a": 1, "b": 2}
>>> y = {"b": 10, "c": 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{"a": 1, "b": 10, "c": 11}

How can I get that final merged dictionary in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I"m looking for as well.)

5839

Answer #1

How can I merge two Python dictionaries in a single expression?

For dictionaries x and y, z becomes a shallowly-merged dictionary with values from y replacing those from x.

  • In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:

    z = x | y          # NOTE: 3.9+ ONLY
    
  • In Python 3.5 or greater:

    z = {**x, **y}
    
  • In Python 2, (or 3.4 or lower) write a function:

    def merge_two_dicts(x, y):
        z = x.copy()   # start with keys and values of x
        z.update(y)    # modifies z with keys and values of y
        return z
    

    and now:

    z = merge_two_dicts(x, y)
    

Explanation

Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:

x = {"a": 1, "b": 2}
y = {"b": 3, "c": 4}

The desired result is to get a new dictionary (z) with the values merged, and the second dictionary"s values overwriting those from the first.

>>> z
{"a": 1, "b": 3, "c": 4}

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

z = {**x, **y}

And it is indeed a single expression.

Note that we can merge in with literal notation as well:

z = {**x, "foo": 1, "bar": 2, **y}

and now:

>>> z
{"a": 1, "b": 3, "foo": 1, "bar": 2, "c": 4}

It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What"s New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy()
z.update(y) # which returns None since it mutates z

In both approaches, y will come second and its values will replace x"s values, thus b will point to 3 in our final result.

Not yet on Python 3.5, but want a single expression

If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:

def merge_two_dicts(x, y):
    """Given two dictionaries, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z

and then you have a single expression:

z = merge_two_dicts(x, y)

You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:

def merge_dicts(*dict_args):
    """
    Given any number of dictionaries, shallow copy and merge into a new dict,
    precedence goes to key-value pairs in latter dictionaries.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a to g:

z = merge_dicts(a, b, c, d, e, f, g) 

and key-value pairs in g will take precedence over dictionaries a to f, and so on.

Critiques of Other Answers

Don"t use what you see in the formerly accepted answer:

z = dict(x.items() + y.items())

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you"re adding two dict_items objects together, not two lists -

>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: "dict_items" and "dict_items"

and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power.

Similarly, taking the union of items() in Python 3 (viewitems() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don"t do this:

>>> c = dict(a.items() | b.items())

This example demonstrates what happens when values are unhashable:

>>> x = {"a": []}
>>> y = {"b": []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: "list"

Here"s an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:

>>> x = {"a": 2}
>>> y = {"a": 1}
>>> dict(x.items() | y.items())
{"a": 2}

Another hack you should not use:

z = dict(x, **y)

This uses the dict constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it"s difficult to read, it"s not the intended usage, and so it is not Pythonic.

Here"s an example of the usage being remediated in django.

Dictionaries are intended to take hashable keys (e.g. frozensets or tuples), but this method fails in Python 3 when keys are not strings.

>>> c = dict(a, **b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.

and

Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dictionaries for readability purposes, e.g.:

dict(a=1, b=10, c=11)

instead of

{"a": 1, "b": 10, "c": 11}

Response to comments

Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.

Again, it doesn"t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2:

>>> foo(**{("a", "b"): None})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{("a", "b"): None})
{("a", "b"): None}

This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

More comments:

dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts.

My response: merge_two_dicts(x, y) actually seems much clearer to me, if we"re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

{**x, **y} does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.

Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first"s values being overwritten by the second"s - in a single expression.

Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:

from copy import deepcopy

def dict_of_dicts_merge(x, y):
    z = {}
    overlapping_keys = x.keys() & y.keys()
    for key in overlapping_keys:
        z[key] = dict_of_dicts_merge(x[key], y[key])
    for key in x.keys() - overlapping_keys:
        z[key] = deepcopy(x[key])
    for key in y.keys() - overlapping_keys:
        z[key] = deepcopy(y[key])
    return z

Usage:

>>> x = {"a":{1:{}}, "b": {2:{}}}
>>> y = {"b":{10:{}}, "c": {11:{}}}
>>> dict_of_dicts_merge(x, y)
{"b": {2: {}, 10: {}}, "a": {1: {}}, "c": {11: {}}}

Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge".

Less Performant But Correct Ad-hocs

These approaches are less performant, but they will provide correct behavior. They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)

You can also chain the dictionaries manually inside a dict comprehension:

{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7

or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2

itertools.chain will chain the iterators over the key-value pairs in the correct order:

from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2

Performance Analysis

I"m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)

from timeit import repeat
from itertools import chain

x = dict.fromkeys("abcdefg")
y = dict.fromkeys("efghijk")

def merge_two_dicts(x, y):
    z = x.copy()
    z.update(y)
    return z

min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))

In Python 3.8.1, NixOS:

>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux

Resources on Dictionaries

5839

Answer #2

In your case, what you can do is:

z = dict(list(x.items()) + list(y.items()))

This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict"s value:

>>> x = {"a":1, "b": 2}
>>> y = {"b":10, "c": 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{"a": 1, "c": 11, "b": 10}

If you use Python 2, you can even remove the list() calls. To create z:

>>> z = dict(x.items() + y.items())
>>> z
{"a": 1, "c": 11, "b": 10}

If you use Python version 3.9.0a4 or greater, then you can directly use:

x = {"a":1, "b": 2}
y = {"b":10, "c": 11}
z = x | y
print(z)
{"a": 1, "c": 11, "b": 10}

5839

Answer #3

An alternative:

z = x.copy()
z.update(y)

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method