Dictionary update() method Python

The Python dictionary update() method is used for updating any values in the dictionary or you can use update() to add more ‘key:value’ pair in the dictionary.There are two ways to use the update() method and they are shown below

Link Dictionary data type

In the first method we will pass the key:value pair inside the braces({}) as the argument to the update() method.You can pass a new key:value pair which will be added to the dictionary or the key may already exist in the dictionary.If the key already exist in the dictionary then only the value gets update.

>>> d={12:1 ,67:6 , "pup":'p' , 34.67:34}
>>> d.update( {12:45} ) #adding new key:value
>>> d
{12: 45, 67: 6, 'pup': 'p', 34.67: 34}
>>> d.update( {"pup":'PUPPY'} ) #updating value of existing key
>>> d
{12: 45, 67: 6, 'pup': 'PUPPY', 34.67: 34, 'q': 0}

With this method you can also add more than one item at a time.

 
>>> d={}
>>> d1.update( {100:10000 , 90:'Ninety'} )
>>> d1
{100: 10000, 90: 'Ninety'}
>>> d1.update( {23:46 , 'T':'ttt' , 45.66:"Randome" } )
>>>> d1
{100: 10000, 90: 'Ninety', 23: 46, 'T': 'ttt', 45.66: 'Randome'}

The second method does not use braces to pass argument to the method.The format of passing the item in this case is to use ‘equal to'(=) sign between the key and value.Also note with this method you can add item having only string as key and number as value.If the key is number or the value is string then you will most probably get an error.

>>> d2={ 'Ten':10 , 100:"hundred" , 'Post-office':'PO' , 78:'7878'}
>>> d2.update( New=100) #adding new item
>>> d2
{'Ten': 10, 100: 'hundred', 'Post-office': 'PO', 78: '7878', 'New': 100}
>>> d2.update( Ten=10000 ) #updating existing item
>>> d2
{'Ten': 10000, 100: 'hundred', 'Post-office': 'PO', 78: '7878', 'New': 100}
>>> d2.update( Name=890 , Hello=910  ) #adding two items
>>> d2
{'Ten': 10000, 100: 'hundred', 'Post-office': 'PO', 78: '7878', 'New': 100, 'Name': 890, 'Hello': 910}
>>> #Cases when you get error
>>> d2.update( 500="Five hundred" ) #Error!!
SyntaxError: keyword can't be an expression
>>> d2.update( Key=value ) #Error!!
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    d2.update( Key=value )
NameError: name 'value' is not defined


Leave a Reply

Your email address will not be published. Required fields are marked *