Problem in inserting new key pairs in Dictionary Python

s = "eat"
for i in s:
    d = dict()
    d[i] = i
    if i in d:
        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

>Solution :

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.

Leave a Reply