Home > Software design >  Renaming a dict key to value of other key
Renaming a dict key to value of other key

Time:10-03

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

CodePudding user response:

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}
  • Related