Reputation: 13
word = 'EVAPORATE'
lettersWord = list(word)
d = {}
for elem in lettersWord:
d[elem] = '_'
print(d)
This returns:
{'E': '_', 'V': '_', 'A': '_', 'P': '_', 'O': '_', 'R': '_', 'T': '_'}
Though what I want it to return is:
{'E': '_', 'V': '_', 'A': '_', 'P': '_', 'O': '_', 'R': '_', 'A': '_', 'T': '_', 'E': '_'}
Thanks for any help!
Upvotes: 1
Views: 2180
Reputation: 46
If you want to use some type of list data structure you could try a 2D array
Or if you are fine with using a string to show your output you could do that as well
2D array implementation
word = 'EVAPORATE'
lettersWord = list(word)
d = []
for elem in range(len(lettersWord)):
d.append([]) #here we make our sublist
d[elem].append(lettersWord[elem]) #here we append the current character of lettersWord to the current sublist
d[elem].append('_') #here we append the underscore as our marker
for i in d:
print(i)
String implementation
ourString = ''
for i in word:
ourString += i+' : _ \n' #here we append our : _ and a newline as our marker
print(ourString)
Output #1:
['E', '_']
['V', '_']
['A', '_']
['P', '_']
['O', '_']
['R', '_']
['A', '_']
['T', '_']
['E', '_']
Output #2
E : _
V : _
A : _
P : _
O : _
R : _
A : _
T : _
E : _
Hope this helps!
Upvotes: 0
Reputation: 123443
The keys of a dictionary must be unique, so you can't have duplicates. One way to make the keys unique in this case would be to make them a tuple
that contains the letter and its corresponding string index.
Here's what I mean:
from pprint import pprint
word = 'EVAPORATE'
d = {}
for (i, letter) in enumerate(word):
d[i, letter] = '_'
pprint(d)
Output:
{(0, 'E'): '_',
(1, 'V'): '_',
(2, 'A'): '_',
(3, 'P'): '_',
(4, 'O'): '_',
(5, 'R'): '_',
(6, 'A'): '_',
(7, 'T'): '_',
(8, 'E'): '_'}
Upvotes: 0
Reputation: 71451
Create a list of the duplicate key's values:
from collections import defaultdict
word = 'EVAPORATE'
d = defaultdict(list)
for i in word:
d[i].append("_")
Output:
{'A': ['_', '_'], 'E': ['_', '_'], 'O': ['_'], 'P': ['_'], 'R': ['_'], 'T': ['_'], 'V': ['_']}
Upvotes: 1