The key and value of the Python dictionary keep changing.

Asked 2 years ago, Updated 2 years ago, 111 views

 for _ in range(NUM_OF_STRING):
    sortedDict[_] = {str(string[_]), sortIndexArr[_]}

for __ in range(NUM_OF_STRING):
    print(sortedDict[__])

This is the code, and if you run it,

{0, "['P', 'S', 'R', 'S', 'P', 'P', 'S', 'E', 'P', 'E', 'R', 'S', 'R', 'R', 'P', 'S', 'P', 'R']"}
{0, "['P', 'S', 'D', 'S', 'P', 'E', 'E', 'P', 'P', 'E', 'S', 'E', 'D', 'E', 'D', 'P', 'E', 'S']"}
{0, "['R', 'R', 'D', 'D', 'E', 'E', 'D', 'P', 'P', 'D', 'E', 'D', 'D', 'D', 'D']"}
{0, "['R', 'R', 'R', 'P', 'R', 'S', 'S', 'S', 'E', 'E', 'D', 'S', 'S', 'R', 'D', 'E', 'P', 'S', 'R']"}
{0, "['S', 'S', 'E', 'S', 'R', 'E', 'P', 'P', 'S', 'R', 'E', 'D', 'R', 'P', 'R', 'E', 'S', 'D', 'P']"}
{0, "['E', 'S', 'P', 'D', 'D', 'S', 'R', 'D', 'D', 'D', 'D', 'D', 'E', 'R']"}
{0, "['E', 'P', 'S', 'S', 'D', 'S', 'R', 'D', 'P', 'P', 'S', 'P', 'D', 'R', 'S']"}
{"['D', 'R', 'R', 'S', 'E', 'R', 'P', 'R', 'R', 'P', 'E', 'P', 'R', 'S', 'D', 'S', 'D', 'E']", 0}
{"['P', 'D', 'S', 'S', 'P', 'E', 'E', 'P', 'R', 'R', 'P', 'E', 'D', 'R', 'E', 'R', 'E', 'D', 'R']", 0}
{"['P', 'R', 'R', 'S', 'S', 'R', 'E', 'R', 'P', 'S', 'R', 'D', 'R', 'E', 'S', 'R', 'S', 'R', 'P', 'S']", 0}

In this way, the value of sortIndexArr[_] appears on the left, and the value of string[_] appears.

The value of string[_] is multiple characters in the list The value of sortIndexArr[_] is a number.

python python3 dictionary

2022-09-22 13:08

2 Answers

There is no order because sortedDict[k] is set. (I'm sure it's inside.) So unlike list or tuple, print comes out without order.


2022-09-22 13:08

(Corrected) The answer below is an incorrect answer, so you can ignore it.

OrderedDict

https://www.geeksforgeeks.org/ordereddict-in-python/

You can use this.

However, since Python 3.7, the dictionary also remembers the insertion order, so the use of OrderedDict, which occupies more memory, is no longer necessary to use it only to guarantee the order in simple rotation.

https://docs.python.org/3/library/collections.html#ordereddict-objects


2022-09-22 13:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.