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:

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.

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.

Was this post helpful?

Leave a Reply

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