Python dictionary update() - Update the dictionary with the other dictionary or the key-value pairs

The update() updates a dictionary with the other dictionary.

d = {'x': 1, 'y': 2}
d2 = {'m': 4, 'n': 5}

d.update(d2)

print(d)
# {'x': 1, 'y': 2, 'm': 4, 'n': 5}

If an appending data has keys included in the dictionary's keys, their values are replaced with new ones.

d = {'x': 1, 'y': 2}
d2 = {'x': 4}

d.update(d2)

print(d)  # {'x': 4, 'y': 2}

Both dictionaries have x key and 1 is replaced with 4. So update() inserts new pairs and updates old pairs.

Keyword arguments

The update() can take keyword arguments. The keywords are updating keys.

d = {'x': 1, 'y': 2}

d.update(m=5, n=7)

print(d)
# {'x': 1, 'y': 2, 'm': 5, 'n': 7}

The keywords don't need single or double quotes and can't be numbers.

d = {'x': 1, 'y': 2}

d.update(2='a')
# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

Update values

You can add a key-value pair to a dictionary like this.

d = {'A': 2, 'B': 5}

d['C'] = 3

print(d)
# {'A': 2, 'B': 5, 'C': 3}

If you set the key that the dictionary has already had, the value of it is replaced.

d = {'A': 2, 'B': 5}

d['B'] = 100

print(d)
# {'A': 2, 'B': 100}

Dictionary unpacking

From Python 3.5, it's possible to update a dictionary or concatenate dictionaries with Python dictionary unpacking.

d = {'x': 1, 'y': 2}
d2 = {'m': 4, 'n': 5}

d3 = {**d, **d2}

print(d3)
# {'x': 1, 'y': 2, 'm': 4, 'n': 5}

** is so-called unpacking, generating multiple pairs in a dictionary. **d means d's pairs and **d2 means d2's pairs.

Trivia

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

d.update('')

print(d)
# {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

It's nonsense but interesting.

Comments

Powered by Markdown

More