Order of displayed totals for 9. Something of Value


#1

Based on my calculations I imagine the program takes the keys in the arrays one by one in order but it seems it doesn’t.

Anyone knows why?

The colored values on the right is how I assumed it should have been displayed. It seems it displays them randomly.


#2

Hello :slight_smile:

Quote from documentation:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

There is also a OrderedDict collection which preserves order. You can import it using:

from collections import OrderedDict

#3

ask @ mtf.
I asked this about ordering a dictionary:


#4

I believe this is a little off topic because @jedgeorge asked why dictionary does not maintain original order, and you asked about maintaining different order - sorted.

However, I would like to add something in this matter. As @mtf pointed out, if we want to access a dictionary in a sorted way we can use a list of keys and simply sort it. But this is a rather strange request (in regards to standard usage of dictionaries) and sorting is quite expensive so here comes the question - what if we want to maintain keys in a sorted manner all the time?

As I said before, it’s important to use the right data structures. If you want to maintain original order there is a OrderedDict and if you want to maintain sorted order of keys you can use awesome module SortedContainers. Here is an example of using SortedDict -> https://repl.it/@factoradic/SortedDict-example


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.