Dictionary update() method in Python

Spread the love

update() method –

The update method updates a dictionary with the elements from another dictionary or an iterable with key value pairs.

syntax of update –


Let’s say we have a two dictionaries which contains some stock prices.

In [1]: prices = {'icici': 710, 'reliance': 2617}

In [2]: prices2 = {'airtel': 737, 'sbi': 495}

And you want to update the first dictionary with all the stock prices from the second dictionary.

In [3]: prices.update(prices2)

In [4]: prices
Out[4]: {'icici': 710, 'reliance': 2617, 'airtel': 737, 'sbi': 495}

In [5]: prices2
Out[5]: {'airtel': 737, 'sbi': 495}

When the keys is not present then update method will add the keys to the dictionary. But when it is present then update method will update the value associated with the key.

Let’s say that the price of sbi stock changed and you want to update that.

In [6]: prices.update({'sbi': 1000})

In [7]: prices
Out[7]: {'icici': 710, 'reliance': 2617, 'airtel': 737, 'sbi': 1000}

Rating: 1 out of 5.

Leave a Reply