Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update method in Python dictionary

I was trying to update values in my dictionary, I came across 2 ways to do so:

product.update(map(key, value))  product.update(key, value) 

What is the difference between them?

like image 903
Max Kim Avatar asked Jul 09 '13 11:07

Max Kim


People also ask

What is update method in dictionary python?

Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. Syntax: dict.update([other]) Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters.

What is the correct syntax of the update () method?

The UPDATE statement has the following form: UPDATE table_name SET column_name = value [, column_name = value ...] [ WHERE condition]

Can we update key in dictionary python?

Python update() method updates the dictionary with the key and value pairs. It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary.

How do you update list values in a dictionary?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')


1 Answers

The difference is that the second method does not work:

>>> {}.update(1, 2) Traceback (most recent call last):   File "<stdin>", line 1, in <module> TypeError: update expected at most 1 arguments, got 2 

dict.update() expects to find a iterable of key-value pairs, keyword arguments, or another dictionary:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

map() is a built-in method that produces a sequence by applying the elements of the second (and subsequent) arguments to the first argument, which must be a callable. Unless your key object is a callable and the value object is a sequence, your first method will fail too.

Demo of a working map() application:

>>> def key(v): ...     return (v, v) ...  >>> value = range(3) >>> map(key, value) [(0, 0), (1, 1), (2, 2)] >>> product = {} >>> product.update(map(key, value)) >>> product {0: 0, 1: 1, 2: 2} 

Here map() just produces key-value pairs, which satisfies the dict.update() expectations.

like image 124
Martijn Pieters Avatar answered Oct 17 '22 19:10

Martijn Pieters