0

I have a dict with n parameters:

print(table)
{
    "Parameters":{
        "erVersion":"1.0",
        "A":"a",
        "rVersion":"1.0",
        "B":"b",
        "C":"c",
        "Ur":"legislator",
        "RecordSize":"13",
        "classification":"json",
        "compressionType":"none"
    }
}

I wanted to place the parameters A, B and C to the top of parameters. I tried doing this with the following code:

table['Parameters'].move_to_end("C", last=False)
table['Parameters'].move_to_end("B", last=False)
table['Parameters'].move_to_end("A", last=False)

This however doesn't work as of Python 3.5+ (refference:https://stackoverflow.com/a/16664932/7615751)

Is there an alternative to this with newer versions of Python? If a different approach is better I'd also appreciate the suggestion to use it.

I don't want to solve this by defining a fixed parameter order because I have a lot of tables like this with a different number of parameters (they always have the A, B, C parameter though).

ire
  • 491
  • 2
  • 12
  • 26
  • It works for me on 3.8. Do you maybe get "AttributeError: 'dict' object has no attribute 'move_to_end'"? – Reti43 Feb 01 '21 at 13:22
  • Parameters doesn't appear to be an ordered dict in your example – Abdul Aziz Barkat Feb 01 '21 at 13:25
  • @Reti43 Yes exactly. Can I get around that? – ire Feb 01 '21 at 13:29
  • You need to use an [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict), not regular `dict`. The question you linked yourself solves your problem... – Tomerikoo Feb 01 '21 at 13:45
  • Does this answer your question? [How to add an element to the beginning of an OrderedDict?](https://stackoverflow.com/questions/16664874/how-to-add-an-element-to-the-beginning-of-an-ordereddict) – Tomerikoo Feb 01 '21 at 13:45
  • @Tomerikoo Yes, I understand that now. Thank you – ire Feb 01 '21 at 13:48

1 Answers1

1

Let's assume

data = {
    "Parameters":{
        "erVersion":"1.0",
        "A":"a",
        "rVersion":"1.0",
        "B":"b",
        "C":"c",
        "Ur":"legislator",
        "RecordSize":"13",
        "classification":"json",
        "compressionType":"none"
    }
}

You seem to be doing table = OrderedDict(data), which will create said object for only the key 'Parameters'. The value of that, i.e., the inner dictionary, will remain a normal dict, which doesn't support move_to_end(). You can address that with

table['Parameters'] = OrderedDict(table['Parameters'])
Reti43
  • 9,656
  • 3
  • 28
  • 44