I have a large python python created from json data and I am creating a smaller dict from a large one. Some elements of a large vocabulary have a key called "details", and some elements do not. What I want to do is check if a key exists in each entry in the large dictionary, and if not, add the "details" key with the value "No data available" to the new dictionary. I put an example example below as a demo. LargeDict is much larger with many keys in my code, but I keep it simple for clarity.
LargeDict = {'results':
[{'name':'john','age':'23','datestart':'12/07/08','department':'Finance','details':'Good Employee'},
{'name':'barry','age':'26','datestart':'25/08/10','department':'HR','details':'Also does payroll'},
{'name':'sarah','age':'32','datestart':'13/05/05','department':'Sales','details':'Due for promotion'},
{'name':'lisa','age':'21','datestart':'02/05/12','department':'Finance'}]}
This is how I get the data for SmallDict:
SmallDict = {d['name']:{'department':d['department'],'details':d['details']} for d in LargeDict['results']}
I get a key error, however, when one of the large dict entries has no details. Am I saying correctly that I need to use a module DefaultDictor is there an easier way?
source
share