Search code examples
pythonpython-3.xdictionaryprintingenumerate

Updating values in dictionary and using enumerate function and print function giving different functions for the below code


x = {'s': 1, 'd': 2, 'f': 4}
x['s'] = 6
print(x)
for q, w in enumerate(x):
    print(q, w)

The above code is giving different outputs when printing it directly and when using enumerate and printing it.

{'s': 6, 'd': 2, 'f': 4}

0 s   
1 d   
2 f 

Solution

  • You have to iterate through it with dict.items, enumerate just gives the index.

    So try this:

    for q, w in x.items():
        print(q, w)