0

I have class definition like...

class companyInCountry:
    def __init__(self,name,country):
        self.name = name
        self.country = country
        self.amountOwed = defaultdict(int)

And I'm looping through a table that let's say has 6 rows...

COMPANY     COUNTRY  GROSS  NET
companyA    UK       50     40
companyA    DE       20     15
companyA    UK       10     5
companyA    FR       20     10
companyB    DE       35     25
companyB    DE       10     5

What I want at the end of looping through this table is to end up with many company/territory specific objects, e.g.

object1.name = companyA
object1.territory = UK
object1.amountOwed['GROSS'] = 60
object1.amountOwed['NET'] = 45

But what I'm struggling to visualise is the best way to prevent objects being created that have duplicate company/country combinations (e.g. that would happen for the first time on row 3 in my data). Is there some data type or declaration I can include inside my init def that will ignore duplicates? Or do I need to manually check for the existence of similar objects before calling companyInCountry(name,country) to initialise a new instance?

1 Answer 1

1

The simplest way to do this would be to maintain a set of (company, country) tuples which can be consulted before creating a new object. If the pair already exists, skip it, otherwise create the object and add the new pair to the set. Something like

pairs = set()
for row in table:
    if (row.company, row.country) in pairs:
        continue
    pairs.add((row.company, row.country))
    company = CompanyInCountry(row.company, row.country)
    # do something with company

If you want a more object-oriented solution, delegate creation of companies to a collection class that performs the necessary checks before creation.


class CompanyCollection:
    def __init__(self):
        # A list to hold the companies - could also be a dict.
        self._companies = []
        self._keys = set()

    def add_company(self, row):
        key = (row.company, row.country)
        if key in self._keys:
            return
        self._companies.append(CompanyInCountry(*key))
        return

    # Define methods for accessing the companies,
    # or whatever you want
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.