Search code examples
pythonstringdictionaryconcatenation

How can I rewrite this so that it does not repeat?


I'm looking for suggestions on how I could rewrite this so that the code isn't repeating. It's suppose to separate the float(digits) from the string(alphabetical characters) within a dictionary's value, and subtract or add a user's numerical input to the float. Afterwards, it rejoins the digits and the letters, converts them back into a string and stores the value.

An example of what it should do is take "19.0: chicken" from the dictionary, split it, add 3 from the user's input, and return "22.0 chicken" to the dictionary.

if modify_options == "1":
    quantity_value = float(re.findall(r"[0-9]+(?:\.[0-9]*)?", inventory_list[key]) [0]) + quantity
    quantity_measurement = ''.join(re.findall(r'(?i)[A-Z]', str(inventory_list[key])))
    inventory_list[key] = str(quantity_value) + str(quantity_measurement)
    return inventory_list

elif modify_options == "2":
    quantity_value = float(re.findall(r"[0-9]+(?:\.[0-9]*)?", inventory_list[key])[0]) - quantity
    quantity_measurement = ''.join(re.findall(r'(?i)[A-Z]', str(inventory_list[key])))
    inventory_list[key] = str(quantity_value) + str(quantity_measurement)
    return inventory_list

Solution

  • The best practice for this would be wrapping up the code within a function. Infact whenever you find some part of code is repeating multiple times, you are supposed to put it into a function.

    Here's how to do it:

    def update_inventory(key, option, quantity):
      quantity_value = float(re.findall(r"[0-9]+(?:\.[0-9]*)?", inventory_list[key]) [0])
      quantity_measurement = ''.join(re.findall(r'(?i)[A-Z]', str(inventory_list[key])))
      if option=="1":
       quantity_value += quantity
      elif option=="2":
        quantity_value -= quantity
      inventory_list[key] = str(quantity_value) + str(quantity_measurement)
      return inventory_list
    
    #now you can update the inventory_list by calling the function 
    update_inventory(2, "1", 9)
    update_inventory(1, "2", 4)