2

I do understand how to achieve putting letters in a list separated by commas:

e.g.

a = 'hello'

print(list(a))

How can I achieve such an output below?

['h':0, 'e':1, 'l':2, 'l':3, 'o':4]
roganjosh
  • 10,918
  • 4
  • 25
  • 39
Martin
  • 85
  • 4

3 Answers3

1

Since your output is neither a list nor a dict, you would have to format the output from a generator expression with enumerate yourself:

from pprint import pformat
print('[%s]' % ', '.join('%s:%d' % (pformat(n), i) for i, n in enumerate(a)))

This outputs:

['h':0, 'e':1, 'l':2, 'l':3, 'o':4]
blhsing
  • 70,627
  • 6
  • 41
  • 76
1
outa = [(i,w) for w,i in enumerate(a)]
print(outa)
outa = dict() # gives you [("h",0),("e",1),("l",2),("l",3),("o",4)]
for w,i in enumerate(a):
    outa[w] = i
print(outa) # gives you {0:"h",1:"e",2:"l",3:"l",4:"o"}

since you wrote it like a dictionary i asume you want them linked in some way or form dicitionaries cant however have dublicate keys, so i made it to a a tuple, a dicionary can however work if the key becomes the inddex and the key value the letter.

Jonas Wolff
  • 1,454
  • 1
  • 7
  • 15
1

Use enumerate.

Your list looks like a dictionary and will make operations on it a bit tougher.

Almost close:

>>> a = 'hello'
>>> [f'{x}: {i}' for i, x in enumerate(a)]
['h: 0', 'e: 1', 'l: 2', 'l: 3', 'o: 4']

But

A better way to organise your list is to make a list of tuples as follows:

>>> [(x, i) for i, x in enumerate(a)]
[('h', 0), ('e', 1), ('l', 2), ('l', 3), ('o', 4)]

Now, you could easily iterate and perform operations on list.

Austin
  • 24,608
  • 4
  • 20
  • 43