Method Name
update
Method Signature
update([another])
Overview
- Updates the dictionary from another dictionary or another iterable. In case of an iterable, it is to have one or more iterables containing name-value pairs.
Parameters
A dictionary or an iterable containing iterables of name value pairs or keyword arguments of the form name1=value1, name2=value2..nameN=valueN
Return Value
None
Example 1
# Example Python program that updates
# the values present in a dictionary
# using another dictionary
d1 = {1:"a",
2:"b",
3:"c"};
d2 = {1:"z",
2:"y",
3:"x"};
print("d1 - Before update:");
print(d1);
d1.update(d2);
print("d1 - After update:");
print(d1);Output
d1 - Before update:
{1: 'a', 2: 'b', 3: 'c'}
d1 - After update:
{1: 'z', 2: 'y', 3: 'x'}Example 2
# An example Python program that updates
# dictionary keys with new values from
# a tuple of tuples
# Original dictionary
groceryToBuy = {"Maple Syrup" :2,
"Oatmeal" :1,
"White Bread" :4,
"Alfredo Sauce" :1,
"Marinara Sauce" :2,
"Cheddar Cheese" :4,
"Parmesan Cheese" :4,
"Mozzarella Cheese" :3,
"Chicken Broth" :2,
"Tomato Soup" :2,
"Sausage" :8
};
# Tuple of tuples to update certain keys in the
# Original dictionary
groceryUpdates = (("Mozzarella Cheese", 5),
("White Bread", 7),
);
groceryToBuy.update(groceryUpdates);
print("Dictionary after updating from a tuple of tuples:");
print(groceryToBuy);Output
Dictionary after updating from a tuple of tuples:
{'Maple Syrup': 2, 'Oatmeal': 1, 'White Bread': 7, 'Alfredo Sauce': 1, 'Marinara Sauce': 2, 'Cheddar Cheese': 4, 'Parmesan Cheese': 4, 'Mozzarella Cheese': 5, 'Chicken Broth': 2, 'Tomato Soup': 2, 'Sausage': 8}