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:
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.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.
Would not recommend doing it this way as it is very slow. Instead, use:
new_dict = dict(zip(keys, values))
https://stackoverflow.com/questions/209840/how-can-i-make-a-dictionary-dict-from-separate-lists-of-keys-and-values