How do I update my dictionary with values from JSON?
I want to update my dictionary with values from the json_file which is of type dict. Here is the JSON dictionary format that I am working with.
json_file: {
"appointmentDeltaEmployee": {
"SSN": "XXXXXXXX",
"dutyBasis": "1",
"normalHours": 80
},
"deductionsDeltaEmployee": {
"unionDuesAnniversaryDay": null,
"DFASUnionCode": null
},
"followUpDeltaEmployee": [
{
"noac05followUpCode": null,
"followUpCode": "S2",
"followUpDate": "2019-10-01"
}
],
"laborDetailsDeltaEmployee": [
{
"functionalCode": "00",
"fundControlPointFor1stPosition": "001",
"cityTaxSatellite": null,
"fMSFundCode": "012012",
"primaryLaborCodePercentage": 100,
"laborDistributionCode": "BBBB",
"laborcostcenter": "5555"
}
],
"leaveDetailsDeltaEmployee": {
"disabledVeteranLeave": "N",
"leaveGroup": "2",
"leaveRestriction": "N",
"eligibleForLeaveNextPayPeriod": "N"
}
}
As you can see there are 2 keys that have list of dictionary. I need to maintain a specific order for output so I created an ordered dictionary with None values.
ordered_keys = ("leaveGroup", "functionalCode", "DFASUnionCode", "normalHours")
order_dic_keys = OrderedDict((k, None) for k in ordered_keys)
If I print my order_dic_keys this is what I get
OrderedDict([('leaveGroup', None), ('functionalCode', None), ('DFASUnionCode', None), ('normalHours', None)])
I want to use a for loop and update order_dic_keys and add the values of what is in the json_file. This is where I get lost and hit the list of dictionary.
for key in order_dic_keys.keys():
for key2, values in json_file.items(): # key2 is followUpDeltaEmployee, values is [{u'followUpDate': u'2019-10-01', u'noac05followUpCode': None, u'followUpCode': u'S2'}]
if key in json_file.items():
order_dic_keys.update(json_file[values])
My order_dic_keys doesn't get updated. Do I parse out the list and create another dictionary with just key and value pairs? Am I not able to update because I used a tuple to maintain order?
Solution 1:
Instead of processing the data after it has been loaded - you can pass custom functions to json.load / loads which can simplify extraction:
ordered_keys = ("leaveGroup", "functionalCode", "DFASUnionCode", "normalHours")
order_dic_keys = OrderedDict.fromkeys(ordered_keys)
def extract_data(obj):
for key, value in obj:
if key in order_dic_keys:
order_dic_keys[key] = value
>>> json.loads(data, object_pairs_hook=extract_data)
>>> order_dic_keys
OrderedDict([('leaveGroup', '2'),
('functionalCode', '00'),
('DFASUnionCode', None),
('normalHours', 80)])
full code example:
import json
from collections import OrderedDict
def extract_data(obj):
for key, value in obj:
if key in order_dic_keys:
order_dic_keys[key] = value
return dict(obj)
ordered_keys = ("leaveGroup", "functionalCode", "DFASUnionCode", "normalHours")
order_dic_keys = OrderedDict.fromkeys(ordered_keys)
with open("file.json") as f:
json_file = json.load(f, object_pairs_hook=extract_data)
print(order_dic_keys)