Add to dictionary Python | Example code

This is the most used and preferred method to add key-value pair to the dictionary is assign operator. You can also use the update method.

dictionary[key] = value

Example Add to dictionary Python

Simple example code adds keys and values to the dictionary in Python.

Add a new key-value pair to an empty dictionary.

d = {}

d['mynewkey'] = 'mynewvalue'

print(d)

Output:

Add to dictionary Python

Add new keys to a dictionary python

dict_1 = {1: "A", 2: "B"}

dict_1[3] = 'C'

print(dict_1)

Output: {1: ‘A’, 2: ‘B’, 3: ‘C’}

Using update method

a_dictonary = {}
a_dictonary.update({"Key": "Value"})

Example code

d = {'item1': 1, 'item2': 2}

d.update({'item3': 3})

print(d)

Output: {‘item1’: 1, ‘item2’: 2, ‘item3’: 3}

How to add multiple keys and values to the dictionary in Python?

Answer: Create a temporary dictionary that needs to be added to the original dictionary and Update the original dictionary with temp_dict content.

mydict = {'name': 'admin', 'age': 32}

temp_dict = {'addr': 'India', 'hobby': 'blogging'}

mydict.update(temp_dict)

print(mydict)

Output:

{‘name’: ‘admin’, ‘age’: 32, ‘addr’: ‘India’, ‘hobby’: ‘blogging’}

Do comment if you have any doubts and suggestions on this Python dictionary basic topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.