In this tutorial, we will see how to append items to dictionary.
There is no method called append in dictionary in python, you can actually use update method to add key value pairs to the dictionary.
Simplest way to add item to dictionary
1 2 3 4 5 6 7 8 |
dict1={1:"one",2:"two",3:"three"} print(dict1) #append key value pair to dict dict1[4]="four" print(dict1) |
Output:
{1: ‘one’, 2: ‘two’, 3: ‘three’}
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’}
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’}
You can use dictionary’s update method to append dictionary or iterable to the dictionary.
Let’s understand with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
dict1={1:"one",2:"two",3:"three"} print(dict1) #you can add another dictionary to current dictionary by using update method dict2={4:"four",5:"five",6:"six"} dict1.update(dict2) print(dict1) #You can add iterable too using update method as below dict1.update(a=1, b=2, c=3) print(dict1) |
Output:
{1: ‘one’, 2: ‘two’, 3: ‘three’}
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’}
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’, ‘a’: 1, ‘b’: 2, ‘c’: 3}
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’}
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’, 6: ‘six’, ‘a’: 1, ‘b’: 2, ‘c’: 3}
That’s all about appending items to dictionary in python.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.