I have a dictionary that contains a list of dictionaries. I am trying to access each dictionary where key is equal to "normalHours". Once I find that value I need to divide it by 2 and append it as a new key "hoursPerWeek" at the end of each dictionary. Problem I am facing is that the append method appends all the "hoursPerWeek" at the end of the list.
Here is my dictionary
dic = {
"employeeData": [
{
"station": "101",
"dateOfBirth": "11-30",
"employmentDate": "2013-06-16",
"normalHours": 80
},
{
"station": "101",
"dateOfBirth": "12-10",
"employmentDate": "2011-02-13",
"normalHours": 80
},
{
"station": "101",
"dateOfBirth": "05-15",
"employmentDate": "2012-12-02",
"normalHours": 80
}
]
}
My attempt to add the new field to the list of dictionary.
hours_per_week = {}
hours_divide_by_2 = 0
for key, value in dic.items():
if str(key) == "employeeData":
for item in value:
if "normalHours" in item:
# 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
value.append(hours_per_week)
I tried using insert but this wouldn't work as I can't insert the key pair into the end of each dictionary. I want to use the update method but the dictionary is part of the list so update method doesn't exists. I'm looking up list functions that python have and I'm not sure what I can use here. The last thing I want to do is convert the type to a dictionary (use the update method) and then convert it back into a list.