Skip to content

Python add to dict in a loop | Adding item to Dictionary within loop example

  • by

You can add keys and to dict in a loop in python. Add an item to a dictionary by inserting a new index key into the dictionary, then assigning it a particular value.

Python add to the dictionary in a loop example

Simple python code:

Add key and value into a dictionary using for loop.

Here is 2 list one is keys and another one values you can combine the both by suing for-in loop.

dicts = {}

keys = [10, 12, 14, 16]
values = ["A", "B", "C", "D"]

for i in range(len(keys)):
    dicts[keys[i]] = values[i]
print(dicts)

Output:

Python add to dict in a loop

Auto-assign key in range with the given value

dicts = {}
keys = range(4)
values = ["A", "B", "C", "D"]
for i in keys:
    dicts[i] = values[i]
print(dicts)

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

Appending values to dictionary in for loop

dicts = {0: 'A', 0: 'B'}
keys = [10, 12]
values = ["A", "B"]

for i in range(len(keys)):
    dicts[keys[i]] = values[i]
print(dicts)

Output:

{0: ‘B’, 10: ‘A’, 12: ‘B’}

Do comment if you have any doubts and suggestions on this Python dictionary 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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading