Python add to Dictionary

In python, there are multiple ways to add keys or values to dictionary.

You can use assignment operator to add key to dictionary.

# Updates if ‘x’ exists, else adds ‘x’
dic[‘x’]=1

There are other ways to add to dictionay as well in python.

dic.update({‘x’:1})
# OR
dic.update(dict(x=1))
# OR
dic.update(x=1)

Example:

d = {'x':1,'y':2,'z':3}
print("Before:",d)
d['p']='24'
print("After:",d)

Output:

Before: {‘x’: 1, ‘y’: 2, ‘z’: 3}
After: {‘x’: 1, ‘y’: 2, ‘z’: 3, ‘p’: ’24’}

Add multiple keys to dictionary

If you want to add multiple keys in one time, you can use update method.

d = {'x':1,'y':2,'z':3}
print("Before:",d)
p = {'a':4,'b':5}
d.update(p)
print("After:",d)

Output:

Before: {‘x’: 1, ‘y’: 2, ‘z’: 3}
After: {‘x’: 1, ‘y’: 2, ‘z’: 3, ‘a’: 4, ‘b’: 5}

That’s all about Python add to Dictionary.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.