Python update dictionary in function

Updates/Adds multiple items to the dictionary

Usage

The update() method updates the dictionary with the key:value pairs from element.

  • If the key is already present in the dictionary, value gets updated.
  • If the key is not present in the dictionary, a new key:value pair is added to the dictionary.

element can be either another dictionary object or an iterable of key:value pairs (like list of tuples).

Syntax

dictionary.update(element)

Python dictionary update() method parameters
Parameter Condition Description
element Optional A dictionary or an iterable of key:value pairs

Examples

update() method is generally used to merge two dictionaries.

D1 = {'name': 'Bob'}
D2 = {'job': 'Dev', 'age': 25}
D1.update(D2)
print(D1)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}

When two dictionaries are merged together, existing keys are updated and new key:value pairs are added.

D1 = {'name': 'Bob', 'age': 25}
D2 = {'job': 'Dev', 'age': 30}
D1.update(D2)
print(D1)
# Prints {'job': 'Dev', 'age': 30, 'name': 'Bob'}

Note that the value for existing key ‘age’ is updated and new entry ‘job’ is added.

Passing Different Arguments

update() method accepts either another dictionary object or an iterable of key:value pairs (like tuples or other iterables of length two).

# Passing a dictionary object
D = {'name': 'Bob'}
D.update({'job': 'Dev', 'age': 25})
print(D)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}

# Passing a list of tuples
D = {'name': 'Bob'}
D.update([('job', 'Dev'), ('age', 25)])
print(D)
# Prints {'age': 25, 'job': 'Dev', 'name': 'Bob'}

# Passing an iterable of length two (nested list)
D = {'name': 'Bob'}
D.update([['job', 'Dev'], ['age', 25]])
print(D)
# Prints {'age': 25, 'job': 'Dev', 'name': 'Bob'}

key:value pairs can be also be specified as keyword arguments.

# Specifying key:value pairs as keyword arguments
D = {'name': 'Bob'}
D.update(job = 'Dev', age = 25)
print(D)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}

In this Python tutorial, we will discuss Python Dictionary update with a few examples like below:

  • Python Dictionary update method
  • Python Dictionary update value
  • Python Dictionary update value if key exists
  • Python Dictionary update function
  • Python Dictionary update vs append
  • Python Dictionary update key
  • Python Dictionary update vs assignment
  • Python Dictionary update all values
  • Python nested dictionary update
  • Python dictionary update if not exists
  • In this section, we will discuss the python dictionary update. Here we will use the update() method.
  • It is an unordered collection of data values, that is used to store data values like a tuple, which does not like other Data Types that contain only a single value as Python dictionary takes Key value pair.
  • This method updates the dictionary with the key and value pairs. It inserts a key/value if it is not present. It updates the key/value if it already exists in the dictionary.
  • This function does not return any values, rather it updates the same input dictionary with the newly associated values of the keys.

Syntax:

Here is the Syntax of the update() method

dict.update([other])
  • It consists of only one parameter.
    • other: It is a list of key/value pairs.
  • Return: It does not return any value(None).

Example:

Let’s take an example to check how to implement a Python dictionary update

In this example to update the dictionary by passing key/value pair. This method updates the dictionary.

Code:

dict = {'Africa':200,'australia':300,'England':400}
print("Country Name",dict)
dict.update({'China':500})
print("updated country name",dict)

In the above example first, we will be creating a dictionary and assigning a key-value pair. After that calling a method update() and print the result.

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update

  • Another example is to update the dictionary by key/value pair.
  • In this example two values are passed to the Python dictionary and it is updated.

Example:

dict = {'John':200,'Micheal':300,'Smith':400}
print("Name",dict)
dict.update({'Andrew':500,'Hayden':800})
print("updated name",dict)

Here is the Screenshot of the following given code

Python update dictionary in function
Python dictionary update 2nd method

  • Another example is to update the dictionary by key/value pair.
  • In this method we can easily use the * operator.
  • Using this method we can merge old dictionary and new key/value pair in another dictionary.

Example:

dict = {'b': 2, 'c': 3}
  
# will create a new dictionary
new_dict = {**dict, **{'d': 4}} # *operator function
  
print(dict)
print(new_dict)

Here is the Screenshot of the following given code

Python update dictionary in function
Python dictionary update operator

Read Python dictionary append with examples

Python Dictionary update method

  • In this section, we will discuss the python dictionary update method by using the Python update() method.
  • You can also update a dictionary by inserting a new value or a key pair to a present entry or by deleting a present entry.
  • The update() method inserts the specified items into the Python dictionary.
  • The specified items can be a dictionary or iterable elements with key-value pairs.

Syntax:

Here is the Syntax of the update() method

dict.update(iterable)
  • It consists of only one parameter.
    • iterable: It is an object with key value pairs, that will be added to the dictionary

Example:

Let’s take an example to check how to update dictionary items

dict1 = {'Python':200,'Java':300,'C++':400}
print("Languages",dict1)
dict1.update({'Ruby':500,'Pascal':800})
print("updated language",dict1)

Here is the Screenshot of the following given code

Python update dictionary in function
Python dictionary update method

Read Python Dictionary index

Python Dictionary update value

  • In this section, we will discuss the python dictionary update value.
  • To update the value of an existing key in the Python dictionary, You have to create a temporary dictionary containing the key with a new value and then pass this dictionary to the update() function.
  • Update() function accepts an iterable another parameter of key-value pairs (dictionary or list) as an argument and then updates the values of keys from the iterable object to the dictionary.

Syntax:

Here is the Syntax of the update function

dict.update([other])
  • Return: It does not return any value(None).

Example:

Let’s take an example to check how to update values in the dictionary

dict1 = {'Germany':200,'France':300,'Paris':400}
print("Country name",dict1)
dict1.update({'France':600})
print("updated value",dict1)

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update value

Read How to convert dictionary to JSON in Python

Updated Nested Python dictionary

  • Another example is to update value in a Python dictionary.
  • You can update the value of a specific item by referring to its key name.
  • In this example we can easily use updating nested dictionary method.
  • In Python, Nested dictionaries will be created by the comma-within the enclosed curly brackets.
  • Value to a specified key in a nested dictionary can be included using its Key method. But, we can do this, first, you have to create an empty dictionary even before assigning values to respective keys.

Syntax:

Here is the Syntax of the Python nested dictionary

dict[out-key][in-key]='new-value'

Example:

Let’s take an example to check how to update values in the Python dictionary

dict = { 'student1_info':{'name':'John','Roll-no':32},'student2_info':{'name':'Micheal','Roll-no':24}}
print("Dictionary before updation:",dict)
dict['student1_info']['Roll-no']=78 # nested dictionary

print("Dictionary after updation:",dict)

In the above example, we have updated the value of the inner key:’Rollno’ of the outer key:’student1_info1′ to 78.

Here is the Screenshot of the following given code

Python update dictionary in function
Python dictionary update value nested method

Read Python dictionary filter + Examples

Python Dictionary update value if key exists

  • In this section, we will discuss the python dictionary update value if key exists.
  • In this method we can easily use the function inbuilt method keys().
  • This method returns a list of all the available keys in the dictionary. With the Inbuilt method Keys(), use the if statement and the ‘in’ operator to check if the key exists in the dictionary or not.
  • If the key exists then it will update the value in the dictionary.

Example:

Let’s take an example and check how to update values if the key exists in the dictionary.

def checkKey(dict, key):
      
    if key in dict.keys():
        print("Key exist, ", end =" ")
        dict.update({'m':600})
        print("value updated =", 600)
    else:
        print("Not Exist")
dict = {'m': 700, 'n':100, 't':500}
  
key = 'm'
checkKey(dict, key)
print(dict)

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update value if the key exists

Read Python Concatenate Dictionary

Another method for update value if key exists in dictionary

  • Let us see, how to update value if key exists in a Python dictionary by using inbuilt method has_key().
  • This function is used to determine whether the key exists in the dictionary, if the key is in the dictionary dict returns true, otherwise returns false.
  • With the Inbuilt function has_key(), use the if statement to check if the key is available in the dictionary or not.

Syntax:

Here is the Syntax of the has_key() method

dict.has_key(key)
  • It consists of only one parameter
    • Key: This is the key pair that is to be searched in the dictionary.

Example:

Let’s take an example and check how to update values if the key exists in the dictionary.

def checkKey(dict, key):
      
    if dict.has_key(key):
        print ("Exists, value updated =", dict[key])
    else:
        print ("Not Exists")
  
# Driver Function
dict = {'u': 400, 't':100, 'c':300}
key = 'w'
checkKey(dict, key)  

In the above example, we have to use the has_key() function which will throw an error as a ‘dict’ object has no attribute ‘has_key’ because the has_key() method has been removed from Python Version 3.

Here is the Screenshot of the following given code

Python update dictionary in function
Python dictionary update value if the key exists an error message

Solution

Has_key method can only be used in the python 2.7 version

Here is the Screenshot of this error message solution

Python update dictionary in function
Python dictionary update value if key exists has_key method

Read Python Dictionary sort

Python Dictionary update vs append

  • In this section, we will discuss the python dictionary update vs append.
  • In this method we can easily use the functions update() and append().
  • In this method, We can easily make use of the built-in function append() to add the values to the keys to the dictionary. To add an element using append() to the dictionary, we have first to find the key to which we need to append. In the case of update() function is used to update a value associated with a key in the input dictionary.
  • This function does not return any values, nor it updates the input dictionary with the newly present values of the keys. While in the case of the append() function you can add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.

Syntax:

Here is the Syntax of the update() function

dict.update([other])

Example:

Let’s take an example to check how to implement the update() and append() functions.

dict = {'Mango':300,'Apple':600,'Orange':900}
print("Fruits Name",dict)
dict.update({'Grapes':500}) # update function
print("updated Fruits name",dict)

my_dict = {"Name":[],"Address":[],"Age":[]};

my_dict["Name"].append("John")
my_dict["Address"].append("England")
my_dict["Age"].append(30)	
print(my_dict)

In the above example first, we will be creating a dictionary and assign a key-value pair. After that calling a method update() and print the result. In append() function consider you have a dictionary, the keys in the dictionary are Name, Address, and Age. Using the append() method we can update the values for the keys in the dictionary.

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update vs append

Python Dictionary update key

  • In this section, we will discuss the python dictionary update key.
  • The nearest thing we can do is to save the value with the old key, remove it, then add a new value with the replacement key and the saved value.
  • In this example, we can easily call dict.pop(key) to update an old key from dict and return its value. With the same dictionary, assign a new key-value pair to the dictionary.
  • The python pop() method removes an element from the dictionary. It removes the element which is associated with the specified key.

Syntax:

Here is the Syntax of pop() method

dict.pop(key,default)
  • It consists of few parameters
    • Key: The key is to being removed from the dictionary.
    • Default: (It’s an optional parameter) The value is to be returned if the key is not found in the dictionary.
  • Return: Returns the value associated with the key. If a key is not found in the dictionary, then it returns the by default value if the default parameter is specified. If the key is not found and the default parameter is not specified, then it throws a key error.

Example:

Let’s take an example to check how to update the key in the dictionary

romanNumbers = {'II':1, 'IV':2, 'III':3, 'V':4, 'VI':5 }
UpdateValue = romanNumbers.pop('V')
print("The popped element is: ", UpdateValue)
print("Updated dictionary: ",romanNumbers)

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update key

  • In case If the key is not found and the default parameter is not specified a key error is raised.

Example:

romanNumbers = {'II':1, 'IV':2, 'III':3, 'V':4, 'VI':5 }
UpdateValue = romanNumbers.pop('VII')
print("The popped element is: ", UpdateValue)

Here is the Screenshot of the following given code

Python update dictionary in function
The python default parameter is not specified

Another method to update key in dictionary

  • In this method, we can easily use the Python zip() function.
  • Suppose if we want to update all keys of the dictionary then we need to use the zip() function.
  • The zip() function creates a sequence that will aggregate elements from two or more iterables.

Example:

Let’s take an example to check how to update the key in the dictionary

mydict = {'John': 1, 'Micheal' : 5, 
            'James' : 10, 'Potter' : 15}
  

mylist = ['m', 'n', 'o', 'p']
print ("initial  dictionary", mydict)
res_dict = dict(zip(mylist, list(mydict.values())))
print ("Updated dictionary", str(res_dict))

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update key zip method

Python Dictionary update vs assignment

  • In this section, we will discuss the python dictionary update vs assignment.
  • In this method, You can use the notation, which can access the key, or creating a new key using square brackets and then providing the opposite value.
  • Also, you can use the dictionary method update() to update a key in an existing dictionary.
  • To add a new key to the dictionary we can simply use the notation with the new one and assign its value using the assignment operator =.

Example:

dict1 = {'Perl':200,'Mongodb':300,'SQL':400}
print("Languages",dict1)
dict1.update({'Ruby':500,'Pascal':800}) #update function
print("updated language",dict1)
 
Mobilename = {'samsung': 100, 'Oppo': 50}

print("Original name:", Mobilename)
Mobilename['Apple'] = 80 # assignment operator

print("Updated name:", Mobilename)

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update vs assignment

Python Dictionary update all values

  • In this section, we will discuss the python dictionary update all values. We can easily do this by using update() function.
  • The python update() method updates the dictionary with the key and value pairs. It inserts a key/value if it is not present. It updates the key/value if it is already present in the dictionary.
  • This function will help the user to update all the values in the Python dictionary.

Syntax:

Here is the Syntax of the update() method

dict.update([other])
  • Return: It does not return any value(none)

Example:

my_dict = {'Italy':200,'Japan':300,'Canada':400}
print("Country name",my_dict)
my_dict.update({'Italy':600,'japan':900,'Canada':250})
print("updated all values:",my_dict)

Here is the Screenshot of the following given code

Python update dictionary in function
Python Dictionary update all values

The above code we can use to update all values in a Python Dictionary.

Python nested dictionary update

  • In this section, we will discuss python nested dictionary update.
  • To remove an item stored in a nested dictionary, we can easily use the del statement. The del statement removes an object. The del function is like a python break statement.
  • In this method we can easily use the method del()

Example:

employee_info = {
	0: { "emp_name1": "John", "salary": 50, "emp_id": 20 },
	1: { "emp_name2": "Micheal","salary":30, "emp_id": 40 },
2: { "emp_name3": "George", "salary": 90, "emp_id": 60 }
}

del employee_info[2]

print(employee_info)
  • In the above example, we could remove this employee from our nested dictionary.
  • In the example, we used a del statement to remove the value in our nested dictionary whose key was equal to 2. As you can see, this removed the entry for emp_name3 from our nested dictionary.

Here is the Screenshot of the following given code

Python update dictionary in function
Python nested dictionary update

Python dictionary update if not exists

  • In this section, we will discuss Python dictionary update if not exists.
  • In this method we can easily use the function in keyword.
  • The in keyword is used to check if a key is already present in the dictionary.

Example:

mobile = {
  "mobile name": "Samsung",
  "reference_number": "M30",
  "year":2019
}
if "mobile name" in mobile:
  print("key mobile name is exist!")
else:
  print("key mobile name is not exist!")
if "color" in mobile:
  print("key phone is exist!")
else:
  print("key phone is not exist!")

Here is the Screenshot of the following given code

Python update dictionary in function
Python dictionary update if not exists

You may like the following Python tutorials:

  • Python remove substring from a String
  • Python replace a string in a file
  • PdfFileWriter Python Examples
  • Registration form in Python using Tkinter
  • Python NumPy max with examples

In this Python tutorial, we will discuss Python Dictionary update with a few examples like below:

  • Python Dictionary update method
  • Python Dictionary update value
  • Python Dictionary update value if key exists
  • Python Dictionary update function
  • Python Dictionary update vs append
  • Python Dictionary update key
  • Python Dictionary update vs assignment
  • Python Dictionary update all values
  • Python nested dictionary update
  • Python dictionary update if not exists

Python update dictionary in function

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Can you modify a dictionary in a function Python?

Yes you can, dictionary is an mutable object so they can be modified within functions, but it must be defined before you actually call the function. To change the value of global variable pointing to an immutable object you must use the global statement.

How do you use the Update function in a dictionary?

Python Dictionary update() Method The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.

How does update () in Python work?

Python Set update() Method The update() method updates the current set, by adding items from another set (or any other iterable). If an item is present in both sets, only one appearance of this item will be present in the updated set.

Can dictionary values be updated?

As mentioned above a value in a dictionary can be updated by using its key as the key is unique for every value.