Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Renaming a dict key to value of other key

I’m kinda new to python but I have a dict containing sort of key pairs:

{
   "ata_smart_attributes_table_0_name":"Raw_Read_Error_Rate",
   "ata_smart_attributes_table_0_raw_value":0,
   "ata_smart_attributes_table_7_name":"Power_On_Hours",
   "ata_smart_attributes_table_7_raw_value":1046,
}

I want to rename the ‘..0_name’ key to the value of that key.
And at the same time the ‘..0_raw_value’ value, has to become the value of the ‘..0_name’ key like so:

{
   "Raw_Read_Error_Rate":0,
   "Power_On_Hours":1046,
}

I’ve been breaking my head over this, any suggestions?
Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try:

dct = {
    "ata_smart_attributes_table_0_name": "Raw_Read_Error_Rate",
    "ata_smart_attributes_table_0_raw_value": 0,
    "ata_smart_attributes_table_7_name": "Power_On_Hours",
    "ata_smart_attributes_table_7_raw_value": 1046,
}

out = {
    v: dct[k.rsplit("_", maxsplit=1)[0] + "_raw_value"]
    for k, v in dct.items()
    if k.endswith("_name")
}

print(out)

Prints:

{"Raw_Read_Error_Rate": 0, "Power_On_Hours": 1046}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading