简体   繁体   中英

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?

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.

You could use collections.defaultdict if you want to create an entry in your dict automatically. However, if you don't, and just want "Not available" (or whatever), then you can just assign to the dict as d[key] = v and use d.get(k, 'Not available') for a default value

get(key, defaultVar)缺少'details'get(key, defaultVar)请使用get(key, defaultVar)方法提供默认值:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM