I'm trying to create a new dictionary from an old one to get only the values I'll new in a df in the future. But the function I created is returning always the same key+values.
def load_data():
with open('./data/awards.json', 'r') as file:
json_file = json.load(file)
events_dict = {}
for data_raw in json_file:
events_dict['event'] = (data_raw['Event'])
#form categories_list
categories_list = []
for all_data in data_raw['Data']:
for awards_data in all_data['nomineesWidgetModel']['eventEditionSummary']['awards']:
#check if it's a premium category
if categories_data['isPremiumCategory'] == True:
for categories_data in awards_data['categories']:
categories = {}
categories['category_name'] = (categories_data['categoryName'])
#form nomination_list
nomination_list = []
for nominations_data in categories_data['nominations']:
primary_nominees = nominations_data['primaryNominees']
if len(primary_nominees)>0:
nominee1 = primary_nominees[0]['name']
secondary_nominees = nominations_data['secondaryNominees']
if len(secondary_nominees)>0:
nominee2 = secondary_nominees[0]['name']
nomination_list.append([nominee1, nominee2, nominations_data['isWinner']])
categories['nominations'] = nomination_list
categories_list.append(categories)
events_dict['categories'] = categories_list
return events_dict
My intention is to get for each award the category, nominations an if it is a winner or not. What I'm getting now is 11 times the same event.
I've tried changing the indentation, append the dict to a list first but nothing helped... I'm sure it's something pretty basic, but I'm new to Python and not seeing my error.
json file
Is it possible to do something like this?
Your logic was a bit off. You want to initialise your events_dict = {} in your loop, then you can append that into a list, which I named results.
def load_data():
with open('C:/test/awards.json', 'r') as file:
json_file = json.load(file)
results = [] #<---- initialize result list
for data_raw in json_file:
events_dict = {} #<--- here initialize your dictionary then build it
events_dict['event'] = data_raw['Event']
#form categories_list
categories_list = []
for all_data in data_raw['Data']:
for awards_data in all_data['nomineesWidgetModel']['eventEditionSummary']['awards']:
#check if it's a premium category
for categories_data in awards_data['categories']: #<---- Need to switch this line
if categories_data['isPremiumCategory'] == True: #<---This needs to follow your loop
categories = {}
categories['category_name'] = (categories_data['categoryName'])
#form nomination_list
nomination_list = []
for nominations_data in categories_data['nominations']:
primary_nominees = nominations_data['primaryNominees']
if len(primary_nominees)>0:
nominee1 = primary_nominees[0]['name']
else:
nominee1 = ''
secondary_nominees = nominations_data['secondaryNominees']
if len(secondary_nominees)>0:
nominee2 = secondary_nominees[0]['name']
else:
nominee2 = ''
nomination_list.append([nominee1, nominee2, nominations_data['isWinner']])
categories['nominations'] = nomination_list
categories_list.append(categories)
events_dict['categories'] = categories_list
results.append(events_dict) #<---- once that dictionary is filled, you can append it into that result list, then move on to make a new events_dict with the next iteration
return results
Related
I have been trying to save a CSV file with information to add to db. And, is necessary to remove the single quotes, and ")". I already tried doing the replace but, didn't worked.
Also, I am doing this by an admin view. I add the csv file with informations to create objects on my db. And, it's from multiple tables. I don't know if I am using the right code or logic for this.
def upload_csv(self,request):
form = CSVImportForm(request.POST, request.FILES)
if request.method == "POST":
csv_file = request.FILES['csv_upload']
file_data = csv_file.read().decode("utf-8")
csv_data = file_data.split("\n")
csv_data = file_data.replace("'", "")
try :
for x in csv_data:
fields = x.split(",")
print(fields)
create_hospital = {}
create_hospital['hospital_name'] = fields[0],
create_hospital['hospital_website'] = fields[1],
create_hospital['hospital_fiscalAddress'] = fields[2],
create_hospital['hospital_shippingAddress'] = fields[3],
create_hospital['hospital_region'] = fields[4],
create_hospital['country'] = fields[5],
create_hospital['hospital_contactPerson'] = fields[6],
create_hospital['hospital_contactPhone'] = fields[7],
create_hospital['hospital_contactEmail'] = fields[8],
create_hospital['hospital_ImageLogo'] = fields[9]
created_hospital = HospitalViewRoleForUsers.objects.create(**create_hospital)
create_users = {}
create_users['FKLab_User'] = fields[0],
create_users['user_type'] = "1",
create_users['email'] = fields[11],
create_users['password'] = BaseUserManager().make_random_password(8),
create_users['name'] = fields[10],
# create_users['FKLab_User'] = created_hospital.id
# create_users['user_type'] = "1"
# create_users['email'] = fields[14],
# create_users['password'] = BaseUserManager().make_random_password(8),
# create_users['name'] = fields[13],
# create_users['FKLab_User'] = created_hospital.id
# create_users['user_type'] = "1"
# create_users['email'] = fields[17],
# create_users['password'] = BaseUserManager().make_random_password(8),
# create_users['name'] = fields[16],
created_users = CustomUser.objects.bulk_create(create_users)
create_roles = {}
create_roles['user_id'] = created_users[0],
create_roles['roles'] = fields[12],
created_roles = RoleHospital.objects.create(create_roles)
except Exception as e:
print("%s", e)
data = {"form": form}
return render(request, "admin/csv_upload.html", data)
Things are being add, except the fact that it adds with single quote and parenthesis.
e.g. : ('salkdklas',)
Thank you.
so I want a function where I read through a file, and creates an instance with every 'recipe'. I also want to create a dictionary, that contains another diciotnary, that points to a list. This is the format I am aiming for:
{cuisine:{course:[recipe_instance...]...}...}
But when I run the version below, I only get one item in every list, although there are more than one item in every list. I'm assuming that I am overwriting a previous value, but I am appending to the list, so i'm not sure if thats correct. Any help helps!
def read_file(filename):
with open(filename,"r", encoding='utf-8') as filein:
filein.readline()
reader = csv.reader(filein)
dic = {}
for line in reader:
srno = line[0]
recipe_name = line[1]
translated_recipe_name = line[2]
ingredients = line[3]
translated_ingredients = line[4]
prep_time = line[5]
cook_time = line[6]
total_time = line[7]
servings = line[8]
cuisine = line[9]
course = line[10]
diet = line[11]
translated_instructions = line[13]
url = line[14]
every_recipe = r.Recipe(srno, translated_recipe_name, translated_ingredients, prep_time,
cook_time, total_time, servings, cuisine, course, diet, translated_instructions, url)
if cuisine not in dic:
dic[cuisine] = {course:[every_recipe]}
elif cuisine in dic:
if course not in cuisine:
dic[cuisine][course] = [every_recipe]
elif course in cuisine:
course.append(every_recipe)
return dic
def WorkLoad():
readWork=open("Todays_Work.txt","r")
for line in readWork.readlines():
WorkLine = line.split()
Order_No = WorkLine[0]
Deliver_Address = WorkLine[1]
Bay_Collection = WorkLine[2]
Stock = WorkLine[3]
print(WorkLine[0],"\n",WorkLine[1],"\n",WorkLine[2],"\n",WorkLine[3])
print(WorkLine)
I am currently started of with this but it only prints out the last line in the text file.
Try below code this will give you collective result in the form of dictionary.
from collections import OrderedDict
result = OrderedDict() #creating a Ordered dictionary
#setting dictionary elements
result["Order_No"] = []
result["Deliver_Address"] = []
result["Bay_Collection"] = []
result["Stock"] = []
def WorkLoad(result):
readWork=open("Todays_Work.txt","r")
for line in readWork.readlines():
WorkLine = line.split()
result["Order_No"].append(WorkLine[0])
result["Deliver_Address"],append(WorkLine[1])
result["Bay_Collection"].append(WorkLine[2])
result["Stock"].append(WorkLine[3])
return result
data = Workload(result) #calling the workload function
print(data) #printing the data
If you wish to print each line, you should add a print statement inside the loop. Or save them to a later use. Probably you want something like this:
Order_No = []
Delivery_Address = []
Bay_Collection = []
Stock = []
def WorkLoad():
readWork=open("Todays_Work.txt","r")
for line in readWork.readlines():
WorkLine = line.split()
Order_No.append(WorkLine[0])
Deliver_Address.append(WorkLine[1])
Bay_Collection.append(WorkLine[2])
Stock.append(WorkLine[3])
print(Order_No[-1], Deliver_Address[-1], Bay_Collection[-1], Stock[-1])
This prints each line during the loop and saves all the fields in the relative lists. I define the lists outside WorkLoad so they are available from other functions you may have. Hope this is helpful.
For some reason my code(following) has brought up a Value Error which I cannot understand. Please evaluate my code too. You can find the project I am trying to do at
http://www.ocr.org.uk/Images/226767-unit-j276-03-programming-project-task-1-sample-non-exam-assessment.pdf
fileid = "details for nea.txt"
ID = []
surname = []
forename = []
dob = []
addr = []
addrT = []
addrTh = []
addrF = []
addrFi = []
homNum = []
gend = []
tutor = []
schoolEm = []
def Read():
file = open(fileid, "r")
Record = file.readline()
for line in Record:
line = line.strip()
A,B,C,D,E,F,G,H,I,J,K,L,M = line.split(',')
ID.append(A)
surname.append(B)
forename.append(C)
dob.append(D)
addr.append(E)
addrT.append(F)
addrTh.append(G)
addrF.append(H)
addrFi.append(I)
homNum.append(J)
gend.append(K)
tutor.append(L)
schoolEm.append(M)
file.close()
def Save():
Record = []
file = open(fileid,"w")
for i in range(len(ID)):
Record.append(ID[i] +","+surname[i]+","+forename[i]+","+dob[i]+","+addr[i]+","+addrT[i]+","+addrTh[i]+","+addrF[i]+","+addrFi[i]+","+homNum[i]+","+gend[i]+","+tutor[i]+","+schoolEm[i]+"\n")
file.writelines(Record)
file.close()
Read()
print(ID)
print(surname)
The Text File I used goes as following:
01,abe,fat,01/02/02,5,Stoney Lane,Stur,Dorset,DR101LM,0123,M,C,email#sc. The lists titled addr, addrT represent the different lines of address.
put last three lines inside main. Value error should go away
I need to access the new information added to data_list in the get_data_list function within the second function which is get_month_averages, but when I try to do that, it says data_list is undefined. How do I do this?
import csv
def get_data_list(data_file):
data_file = open("table.csv", "r")
data_list = []
for line_str in data_file:
data_list.append(line_str.strip().split(','))
return data_list
def get_month_averages(data_list):
date_list = []
vol_list = []
adjclos_list = []
for row in data_list:
date_list.append(row[0])
vol_list.append(row[5])
adjclos_list.append(row[6])
all_list = [date_list, vol_list, adjclos_list]
return all_list
print (get_month_averages(data_list))
This one works:
import csv
def get_data_list():
data_file = open("table.csv", "r")
data_list = []
for line_str in data_file:
data_list.append(line_str.strip().split(','))
return data_list
def get_month_averages(data_list):
date_list = []
vol_list = []
adjclos_list = []
for row in data_list:
date_list.append(row[0])
vol_list.append(row[5])
adjclos_list.append(row[6])
all_list = [date_list, vol_list, adjclos_list]
return all_list
dList = get_data_list()
mAvg = get_month_averages(dList)
print mAvg