Python create a dictionary in the loop | Example code

You can create a dictionary in the loop in python if given an ordered list, and match up the values from the list to ordered numbers.

Example create a dictionary in the loop in Python

Simple python example code:-

Example 1: Assign key from zero.

list1 = [102, 232, 424]
count = 0
d = {}  # Empty dictionary to add values into

for i in list1:
    d[count] = i
    count += 1

print(d)

Output:

Example 2: Using 2 lists for key and values

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:

create a dictionary in the loop Example code

Example: 3 Auto-assign key Using a range

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’}

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