1

I have a list like this:

    data.append(
        {
            "type": type,
            "description": description,
            "amount": 1,
        }
    )

Every time there is a new object I want to check if there already is an entry in the list with the same description. If there is, I need to add 1 to the amount.

How can I do this the most efficient? Is the only way going through all the entries?

sg_sg94
  • 2,248
  • 4
  • 28
  • 56

1 Answers1

1

I suggest making data a dict and using the description as a key.

If you are concerned about the efficiency of using the string as a key, read this: efficiency of long (str) keys in python dictionary.

Example:

data = {}
while loop():  # your code here
    existing = data.get(description)
    if existing is None:
        data[description] = {
            "type": type,
            "description": description,
            "amount": 1,
        }
    else:
        existing["amount"] += 1

In either case you should first benchmark the two solutions (the other one being the iterative approach) before reaching any conclusions about efficiency.

orestisf
  • 1,396
  • 1
  • 15
  • 30