Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key exists in dictionary. If not, append it

I have a large python dict created from json data and am creating a smaller dict from the large one. Some elements of the large dictionary have a key called 'details' and some elements don't. What I want to do is check if the key exists in each entry in the large dictionary and if not, append the key 'details' with the value 'No details available' to the new dictionary. I am putting some sample code below just as a demonstration. The LargeDict is much larger with many keys in my code, but I'm keeping 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 am getting the data for the 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 right in saying I need to use the DefaultDict module or is there an easier way?

like image 272
adohertyd Avatar asked Jul 18 '12 18:07

adohertyd


1 Answers

You don't need a collections.defaultdict. You can use the setdefault method of dictionary objects.

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

As others have noted, if you don't want to add the key to the dictionary, you can use the get method.

here's an old reference that I often find myself looking at.

like image 200
mgilson Avatar answered Nov 15 '22 05:11

mgilson