0

I have an array:

classes = ["banana","mango","apple"]

I am trying to print this array in a specific format where in each element has to be numbered in a particular sequence. The desired output is as follows:

classes = [{"banana" : 1, "mango" : 2, "apple" : 3}]

I tried using a for loop as follows:

classes = ["banana","mango","apple"]
counter = 0
dat = []
for x in classes:
    counter=counter+1
    d = x,":", counter
    dat.append(d)
print(dat)

While this prints

[('banana', ':', 1), ('mango', ':', 2), ('apple', ':', 3)]

this is far from what I require. Can someone help?

jpp
  • 159,742
  • 34
  • 281
  • 339
popeye
  • 281
  • 5
  • 20
  • I would suggest using Python's dictionaries for this purpose, instead of combining into an array – nj2237 Mar 17 '18 at 14:31
  • 1
    @nj2237 thank you. I am new to python and hence didnt know that I could use two lists. It really helped. – popeye Mar 17 '18 at 14:32
  • 1
    You *can* use 2 lists, but it's more efficient to use `enumerate` for your precise task (as in my answer). – jpp Mar 17 '18 at 14:39

1 Answers1

2

You can enumerate the input list and reverse via a dictionary comprehension.

classes = ["banana","mango","apple"]

res = {v: k for k, v in enumerate(classes, 1)}

# {'apple': 3, 'banana': 1, 'mango': 2}

There seems to be no need to put this dictionary in a list, as in your desired output.

jpp
  • 159,742
  • 34
  • 281
  • 339