Python - Dictionary Update Method

Introduction

The update method merges the keys and values of one dictionary into another, blindly overwriting values of the same key if there's a clash:

Demo

D = {'eggs': 3, 'test': 2, 'ham': 1} 
D2 = {'toast':4, 'muffin':5}           # Lots of delicious scrambled order here 
D.update(D2) # w w w.jav a2  s  .  com
print( D )

Result

The dictionary pop method deletes a key from a dictionary and returns the value it had.

Demo

# pop a dictionary by key 
D = {'eggs': 3, 'muffin': 5, 'toast': 4, 'test': 2, 'ham': 1} 
print( D.pop('muffin') )
print( D.pop('toast') )                         # Delete and return from a key 
print( D )

# pop a list by position 
L = ['aa', 'bb', 'cc', 'dd'] 
print( L.pop() )                                # Delete and return from the end 
print( L )
print( L.pop(1) )                               # Delete from a specific position 
print( L )

Result

Related Topic