C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Dictionary update() MethodPython 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. It also allows an iterable of key/value pairs to update the dictionary. like: update(a=10,b=20) etc. Signature and examples of this method are given below. Signatureupdate([other]) Parametersother: It is a list of key/value pairs. ReturnIt returns None. Let?s see some examples of update() method to understand it?s functionality. Python Dictionary update() Method Example 1It is a simple example to update the dictionary by passing key/value pair. This method updates the dictionary. See an example below. # Python dictionary update() Method # Creating a dictionary einventory = {'Fan': 200, 'Bulb':150, 'Led':1000} print("Inventory:",einventory) # Calling Method einventory.update({'cooler':50}) print("Updated inventory:",einventory) Output: Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000} Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50} Python Dictionary update() Method Example 2If element (key/value) pair is already presents in the dictionary, it will overwrite it. See an example below. # Python dictionary update() Method # Creating a dictionary einventory = {'Fan': 200, 'Bulb':150, 'Led':1000,'cooler':50} print("Inventory:",einventory) # Calling Method einventory.update({'cooler':50}) print("Updated inventory:",einventory) einventory.update({'cooler':150}) print("Updated inventory:",einventory) Output: Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50} Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50} Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 150} Python Dictionary update() Method Example 3The update() method also allows iterable key/value pairs as parameter. See, the example below two values are passed to the dictionary and it is updated. # Python dictionary update() Method # Creating a dictionary einventory = {'Fan': 200, 'Bulb':150, 'Led':1000} print("Inventory:",einventory) # Calling Method einventory.update(cooler=50,switches=1000) print("Updated inventory:",einventory) Output: Inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000} Updated inventory: {'Fan': 200, 'Bulb': 150, 'Led': 1000, 'cooler': 50, 'switches': 1000}
Next TopicPython Dictionary
|