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]
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]
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]
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.
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.