The assign operator is the most used and preferred method to add key-value pairs to the dictionary. You can also use the update method.
my_dict[key] = value
Here, my_dict
is the dictionary to which you want to add the key-value pair, key
is the key you want to add, and value
is the value associated with the key.
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 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 or suggestions on this Python dictionary basic topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.