I am new to python and learning the stuff from scratch. One thing I want to do, but couldn't find out how is to create a key-value pair list using the for loop and update just the value. A sample code is:
for i in range(0,6)
#####some code that gives an output integer x.
print(i,x)
The integer x is different for each i. How do I create a list like {0:x0,1:x1,2:x2,3:x3,4:x4,5:x5}, using the for loop?
You're looking for Python Dictionaries.
sample = {}
for i in range(6):
# some code that gives you x
sample[i] = x
print(sample)
Do note, however, that since your keys are just 0, 1, 2 etc., you may want to just use a list instead:
sample = []
for i in range(6):
# some code that gives you x
sample.append(x)
print(sample)
Note that dictionary access using sample[key] will look identical to list access using sample[index] since you're just using consecutive numeric keys.
Is this what you are looking for?
dic = {}
x = "8"
for i in range(6):
#calculate x
dic[i] = int(str(x)+str(i))
print(dic)
{0: 80, 1: 81, 2: 82, 3: 83, 4: 84, 5: 85}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With