1

I am reading configuration data from a YAML file and using that info as a Python dictionary. When I change the value of the keys, the code sorts the keys in the file alphabetically. I want to avoid sorting. Below is the screenshot of how the file looks before and after it gets sorted following the I/O operation.

enter image description here

And here's the code I am using to perform the operation.

def change_last_record_id(record_id, table_ref):
    """
       Used for changing the value of 'last_record_id' in the 'config.yaml' file
       :param rcord_id: record_id: Value that needs to be changed.
       :param record_id: table_ref: Key which contains the value
       :return: None
    """
    data_dictionary = yaml.load(open("config.yaml"), Loader=yaml.FullLoader)
    data_dictionary["last-id-"+table_ref] = record_id
    with open("config.yaml", "w") as f:
        yaml.dump(data_dictionary, f)
Chandral
  • 448
  • 1
  • 3
  • 19
  • 1
    How about his answer: https://stackoverflow.com/a/55171433/3337070 – sshashank124 Jan 09 '20 at 05:58
  • @sshashank124 So now the order of the keys remain as it is but it removes any blank lines or block comments I make with '#' – Chandral Jan 09 '20 at 06:05
  • These questions have already been asked+answered. Refer to the linked duplicates – sshashank124 Jan 09 '20 at 06:07
  • Alright, thanks a lot. – Chandral Jan 09 '20 at 06:12
  • 1
    @Chandral I added a more complete solution [here](https://stackoverflow.com/a/59659659/1307905), I suggest you use that as a template when using ruamel.yaml – Anthon Jan 09 '20 at 08:15
  • 1
    I had the same question, but from ruby. My use case was that I wanted to group remote URLs in the middle of the autogenerated yaml file together, but one link started with "wikipedia" (for a wikipedia-related link). That always got dumped to the end of that .yml file, and since it is a fairly large .yml file, people had to constantly jump to the middle and then to the bottom to view it, if they use a plain text editor. I am glad to not be the only one who sometimes needs to be able to easily tell HOW to store the keys. Alphabetical sorting by default makes sense, but not 100% of the time. – shevy Apr 24 '21 at 15:21

0 Answers0