Check if the key exists in the dictionary. If not, add it

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?

+5
source share
3 answers

Use the method get(key, defaultVar)to supply the default value when the key is missing 'details':

SmallDict = {d['name']:{'department':d['department'],'details':d.get('details','No details available')} for d in LargeDict['results']}
+2
source

You do not need collections.defaultdict. You can use the method setdefaultfor dictionary objects.

d = {}
bar = d.setdefault('foo','bar') #returns 'bar'
print bar # bar
print d  #{'foo': 'bar'}

As others noted, if you do not want to add a key to the dictionary, you can use the method get.

here is the old link that I often find.

+13
source

collections.defaultdict, dict. , , "" ( - ), dict d[key] = v d.get(k, 'Not available')

+4

All Articles