Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python dictionary append

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

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’}

You can use dictionary’s update method to append dictionary or iterable to the dictionary.
Let’s understand with the help of example.

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}

That’s all about appending items to dictionary in python.

The post Python dictionary append appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

Python dictionary append

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×