1
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!

martineau
  • 119,623
  • 25
  • 170
  • 301
Gaurav G.
  • 13
  • 3
  • 2
    You can't. Dictionary's keys must be unique. – DeepSpace Jul 01 '17 at 15:16
  • Use defaultdict function. It's possible see also [link](https://stackoverflow.com/q/10664856/5025009) – seralouk Jul 01 '17 at 15:18
  • 2
    In this case, a dictionary is just not the correct structure (What would `d['E']` mean?) Either use a multiset (Like `collections.Counter`) or a list `[('E', '_'), ('V', '_'), ...]` – Artyer Jul 01 '17 at 15:21

3 Answers3

1

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': ['_']}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

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'): '_'}
martineau
  • 119,623
  • 25
  • 170
  • 301
0

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!

Khalif Ali
  • 46
  • 4