maudev
maudev

Reputation: 1101

Keep elements order inside OrderedDict

I'm new with Python and I'm trying dicts, the problem as you know is that the order inside dicts isn't kept so I'm using OrderedDicts to perform this issue but I have no success.

This is the kind of dict that I'm trying:

numbersDictionary = OrderedDict({ 
      "0":{ (0,1),(1,0),(1,2),(2,1),(2,2),(2,3) },
      "1":{ (1,2),(2,3) },
      "2":{ (0,1),(1,1),(1,2),(2,1),(2,1),(2,2) },
      "3":{ (0,1),(1,1),(1,2),(2,2),(2,3) },
      "4":{ (1,0),(1,1),(1,2),(2,3) },
      "5":{ (0,1),(1,0),(1,1),(2,2),(2,3) },
      "6":{ (0,1),(1,0),(1,1),(2,1),(2,2),(2,3) },
      "7":{ (0,1),(1,2),(2,3) },
      "8":{ (0,1),(1,0),(1,1),(1,2),(2,1),(2,2),(2,3) },
      "9":{ (0,1),(1,0),(1,1),(1,2),(2,2),(2,3) }
    });

So when I do something like this:

print(numbersDictionary.get("5"))

The output:

{(0, 1), (2, 3), (2, 2), (1, 0), (1, 1)}

How can I build my dict of that data in order to get the correct order elements?

Upvotes: 2

Views: 56

Answers (3)

ferhatelmas
ferhatelmas

Reputation: 3978

OrderedDict keeps the order of keys, not values. Here, you want your values ordered so list is the right data structure.

>>> numbersDictionary = { 
  "0": [ (0,1),(1,0),(1,2),(2,1),(2,2),(2,3) ],
  "1": [ (1,2),(2,3) ],
  "2": [ (0,1),(1,1),(1,2),(2,1),(2,1),(2,2) ],
  "3": [ (0,1),(1,1),(1,2),(2,2),(2,3) ],
  "4": [ (1,0),(1,1),(1,2),(2,3) ],
  "5": [ (0,1),(1,0),(1,1),(2,2),(2,3) ],
  "6": [ (0,1),(1,0),(1,1),(2,1),(2,2),(2,3) ],
  "7": [ (0,1),(1,2),(2,3) ],
  "8": [ (0,1),(1,0),(1,1),(1,2),(2,1),(2,2),(2,3) ],
  "9": [ (0,1),(1,0),(1,1),(1,2),(2,2),(2,3) ]
}

>>> numbersDictionary["5"]
>>> [(0, 1), (1, 0), (1, 1), (2, 2), (2, 3)]

Upvotes: 1

Jab
Jab

Reputation: 27485

You’re using the wrong data types in the first place. Your keys are literally string representations of indexes; that’s what lists are for! Use a list to store this data.

As for the set’s, you are most likely aiming to use lists here as well as lists retain order while sets do not, they are “unordered collections of unique elements”.

Below is an example of what I mean:

numbers = [
      [(0,1),(1,0),(1,2),(2,1),(2,2),(2,3)]
      [(1,2),(2,3)],
      [(0,1),(1,1),(1,2),(2,1),(2,1),(2,2)],
      [(0,1),(1,1),(1,2),(2,2),(2,3)],
      [(1,0),(1,1),(1,2),(2,3)],
      [(0,1),(1,0),(1,1),(2,2),(2,3)],
      [(0,1),(1,0),(1,1),(2,1),(2,2),(2,3)],
      [(0,1),(1,2),(2,3)],
      [(0,1),(1,0),(1,1),(1,2),(2,1),(2,2),(2,3)],
      [(0,1),(1,0),(1,1),(1,2),(2,2),(2,3)]
]

With your data stored this way you can access the sub-lists using their index as an int.

>>> numbers[5]
>>> [(0, 1), (1, 0), (1, 1), (2, 2), (2, 3)]

Upvotes: 1

wim
wim

Reputation: 362617

The issue is not the OrderedDict itself, but the use of sets as the dictionary values. Sets are unordered. Use lists instead.

This is a set:

{ (1,2),(2,3) }

This is a list:

[ (1,2),(2,3) ]

Upvotes: 2

Related Questions