As you can see I am using a counter variable to iterate through my JSON file and it's a dictionary that has a list of dictionaries. Once I find the key normalHours I divide it and add it to my dictionary hours_per_week. Then I update the dictionary it is associated with. Is it better to use for i in range instead of the counter? Anything else I can do to clean up or speed up the code?
Here is my json file, I deleted most of the key pairs for easier readability.
{ "employeeData": [ { "normalHours": 80, "givenName": "ROBERTO", }, { "normalHours": 80, "givenName": "HEATHER", }, { "normalHours": 80, "givenName": "PAUL", } ] }
def add_hours_per_week(json_file):
"""
Add new dictionary value hoursPerWeek to our JSON data
"""
# Create new dictionary hours_per_week.
hours_per_week = {}
hours_divide_by_2 = 0
normal_hours_counter = 0
try:
for key, values in json_file.items():
if str(key) == "employeeData":
# JSON is in a list of dictionaries
for item in values:
# If normalHours field is Null, "", or 0 add an empty field
if not item["normalHours"] or item["normalHours"] == 0:
hours_per_week["hoursPerWeek"] = ""
else:
# Divide normalHours by 2 rounded to 2 decimals.
hours_divide_by_2 = round(float(item["normalHours"]) / 2, 2)
hours_per_week["hoursPerWeek"] = hours_divide_by_2
json_file['employeeData'][normal_hours_counter].update(hours_per_week)
normal_hours_counter += 1
print("%d employee updated with hoursPerWeek" % normal_hours_counter if normal_hours_counter <= 1 else
"%d employees updated with hoursPerWeek" % normal_hours_counter)
return json_file
except Exception as e:
print("Exception in add_hours_per_week: ", e)
except
block. \$\endgroup\$