(python) why the result of this code not in right order?

Question:

input:

D = {"apple":44, "cherry":"game"}
for x in D:
    print(x, D[x])
    print(str(x) + ": "+ str(D[x]))

output:

apple 44
apple: 44
cherry game
cherry: game

Isn’t this supposed to be outputted like this in right order?

apple 44
cherry game
apple: 44
cherry: game
Asked By: Kyungjin Kwak

||

Answers:

In each loop you:

  1. print the label and its value;
  2. print the label converted to sting and its value converted to string.

So in the first cycle you have prints on element "apple":44, and in the second one prints on "cherry":"game".

The output is totally right.

Answered By: mikyll98

X start out as apple the first iteration and then goes to cherry the secound iteration

Answered By: Wolf
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.