Home > Mobile >  How to check a substring in a string up until a certain occurrence of a character in python?
How to check a substring in a string up until a certain occurrence of a character in python?

Time:02-15

I receive orders that contain the name of costumer, price of order and the quantity of the order.

The format of the order looks like this: {'first order': ['Alex', '100@2']}

(100 refers to a price and 2 refers to a quantity).

So I have different orders: {'first order': ['Alex', '99@2'], 'second order': ['Ann', '101@2'], 'third order': ['Nick', '110@3']}

We need to compare the prices and see which is the highest price and which is the lowest.

I was thinking of doing this by cutting the substring into two parts, the first part before the '@' symbol and the second part after the '@' symbol, then extract the numbers from the first part and compare them with others.

What's the most efficient way you can tell to solve this issue?

Thank you

CodePudding user response:

I'd suggest to transform the dictionary to a list of dictionaries and convert the string to two floats. For example:

orders = {
    "first order": ["Alex", "99@2"],
    "second order": ["Ann", "101@2"],
    "third order": ["Nick", "110@3"],
}

orders = [
    {
        "order": k,
        "name": name,
        "price": float(pq.split("@")[0]),
        "quantity": float(pq.split("@")[1]),
    }
    for k, (name, pq) in orders.items()
]

Then if you want to find highest and lowest price you can use min/max function easily:

highest = max(orders, key=lambda k: k["price"])
lowest = min(orders, key=lambda k: k["price"])

print(highest)
print(lowest)

Prints:

{'order': 'third order', 'name': 'Nick', 'price': 110.0, 'quantity': 3.0}
{'order': 'first order', 'name': 'Alex', 'price': 99.0, 'quantity': 2.0}
  • Related