Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a key- value pair in a for loop using python and update the value

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?

like image 283
Abhishek V. Pai Avatar asked Oct 28 '25 14:10

Abhishek V. Pai


2 Answers

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.

like image 147
brunston Avatar answered Oct 30 '25 12:10

brunston


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}
like image 33
briancaffey Avatar answered Oct 30 '25 11:10

briancaffey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!