-3
s = "eat"
for i in s:
    d = dict()
    d[i] = i
    if i in d:
        continue
    else:
        d[i] = 1

I have tried several times but it is only appending {'t': 't'} as output, I'm expecting {'e': 'e', 'a': 'a', 't', 't'} as the output

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 2
    You're redifining `d` every iteration. Move it outside of the loop. Also, the first `if` statement always gets triggered and the entire thing is unnecessary. – B Remmelzwaal Mar 07 '23 at 17:06
  • `d = dict()` creates a new dict in each iteration – Ch3steR Mar 07 '23 at 17:06
  • 3
    Please do some basic debugging before posting, e.g. using https://pythontutor.com/python-debugger.html#mode=edit or even just `print`ing things - the problem would become obvious quite quickly. – jonrsharpe Mar 07 '23 at 17:06
  • BTW, welcome to Stack Overflow! Please take the [tour], and check out [ask] for tips for future questions. – wjandrea Mar 07 '23 at 17:07
  • FWIW, you could use a dict comprehension if you'd prefer: `d = {i: i for i in s}` – wjandrea Mar 07 '23 at 17:09
  • Welcome to Stack Overflow. To solve the problem: see the linked duplicate - treating the `s` string as both the key list and the values list. To answer the debugging question - that is effectively a typo, and we generally close such questions because they cannot be helpful to others. My hint is to think carefully about the logic: what happens when the code `d = dict()` runs? In particular, what will happen to any dictionary that was already stored in `d`? Therefore, how many times should this code happen? Therefore, should it be inside the loop, or outside? – Karl Knechtel Mar 07 '23 at 17:12
  • as wjandrea said you can just use [dict comprehension](https://www.programiz.com/python-programming/dictionary-comprehension) like `d = {i: i for i in s}`; but also, you should know that `else` if unnecessary after [`if...continue`](https://www.programiz.com/python-programming/break-continue/#working), and that you can use [`not in`](https://realpython.com/python-in-operator/) instead of *`if _ in __...else`* – Driftr95 Mar 07 '23 at 17:33

1 Answers1

-1

You are creating a new dictionary with each iteration of the loop. As a result, you are getting {'t': 't'} As angwrk stated in his response, you want to declare the dictionary outside of your for loop.