Reputation: 11
class Company:
def __init__(self, company_id, name):
self.company_id = company_id
self.name = name
I have a class named Company
(class shown above), and I am trying to add companies into this program using this JSON file:
[
{
"id": "companyA",
"name": "Apple Farm"
},
{
"id": "companyB",
"name": "Buzzing Bees"
},
{
"id": "companyC",
"name": "Cat Corporate"
},
{
"id": "companyD",
"name": "Dog Dentists Limited"
}
]
Right now I, know how to add each company individually like this:
c = Company(company[0]['id'], company[0]['name'])
However, I want to create all of them with a for
loop which creates these companies, and so that I can access them by their company_id
.
How can I do this?
Upvotes: 1
Views: 695
Reputation: 478
From the looks of your class, it looks as though it is not meant to contain information pertaining to multiple companies. Rather, you should create a separate class instance for each company.
Using the object you provided as such:
companies = [
{
"id": "companyA",
"name": "Apple Farm"
},
{
"id": "companyB",
"name": "Buzzing Bees"
},
{
"id": "companyC",
"name": "Cat Corporate"
},
{
"id": "companyD",
"name": "Dog Dentists Limited"
}
]
you can create a class for each company as such:
company_classes = [Company(company.id, company.name) for company in companies]
this will create a list of company objects.
Upvotes: 0
Reputation: 184
You can first retrieve the JSON code with the json
library:
import json
with open("path/to/file.json") as jsonFile: # Replace "path/to/file.json" with the path to your JSON file
companies = json.load(jsonFile)
Then, you can create a dictionary to store the companies:
companyDict = {}
You then iterate through all the companies in the JSON file. Then, for every dictionary inside the JSON file, create a Company
:
for company in companies:
companyDict[company["id"]] = Company(company["id"], company["name"])
You can then access your company like this:
companyA = companyDict["companyA"] # You can replace the key with the company ID
Upvotes: 1
Reputation: 1086
I dint understand the last part of the question where you say you want to "call them by company IDs"..
If you dont want to handle each objects independently and reference it by their name then storing them in a dict is a useful way. A dictionary comprehension will be the easiest way to do it.
company_objects = {company['id']: Company(company['id'], company['name']) for company in companies}
Now you should be able to access them as company_objects['companyA']
If you change the JSON definition slightly as below:
{
"company_id": "companyA",
"name": "Apple Farm"
}
You will be able to even optimize the dictionary comprehension as below:
{company['company_id']: Company(**company) for company in companies}
Upvotes: 1