Problem in inserting new key pairs in Dictionary Python

Question:

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

Asked By: Prakhar Shukla

||

Answers:

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.

Answered By: D. Rodriguez
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.