Detailed Explanation of Basic Usage of update in python

  • 2021-07-22 09:58:25
  • OfStack

Preface

The Python dictionary update () method is used to update the key/value pairs in the dictionary. It can modify the values corresponding to existing keys or add new key/value pairs to the dictionary.

Grammatical format


d.update(e)

Parameter description

Add the key-value pair in e to the dictionary d, which may be a dictionary or a sequence of key-value pairs. See the example for details.

Return value

This method does not have any return value.

Instances

The following example shows how to use the update () method:


d = { ' one':1,'two':2}

d.update({ ' three':3,'four':4}) #  Biography 1 A dictionary  
print(d)

d.update(five=5,six=6) #  Pass keyword  
print(d)

d.update([( ' seven',7),( ' eight',8)]) #  Biography 1 Contains 1 List of tuples or tuples  
print(d)

d.update(([ ' nice',9],[ ' ten',10]))# Biography 1 Contains 1 Tuples of one or more lists  
print(d)

d.update(zip([ ' eleven','twelve'],[11,12])) #  Biography 1 A zip() Function  
print(d)

d.update(one=111,two=222) #  Use any of the above methods to modify the value corresponding to the existing key  
print(d)

The output result of the above example is:


{ ' one': 1,  ' four': 4,  ' three': 3,  ' two': 2} 
{ ' one': 1,  ' four': 4,  ' three': 3,  ' five': 5,  ' two': 2,  ' six': 6} 
{ ' seven': 7,  ' one': 1,  ' four': 4,  ' three': 3,  ' five': 5,  ' two': 2,  ' six': 6,  ' eight': 8} 
{ ' seven': 7,  ' one': 1,  ' four': 4,  ' three': 3,  ' ten': 10,  ' five': 5,  ' nice': 9,  ' two': 2,  ' six': 6,  ' eight': 8} 
{ ' one': 1,  ' four': 4,  ' three': 3,  ' twelve': 12,  ' ten': 10,  ' seven': 7,  ' six': 6,  ' eleven': 11,  ' two': 2,  ' nice': 9,  ' five': 5,  ' eight': 8} 
{ ' one': 111,  ' four': 4,  ' three': 3,  ' twelve': 12,  ' ten': 10,  ' seven': 7,  ' six': 6,  ' eleven': 11,  ' two': 222,  ' nice': 9,  ' five': 5,  ' eight': 8}

Related articles: