سؤال

I'm dealing with error handling with dictionaries. Is there a slick way to check if each one of these keys is in the dictionary that I'm searching without skipping over them all (by putting them into one try block) if one generates an error?

Obviously I can check for each key one at a time and that works fine, but I'm looking for a nicer/prettier looking way to do it.

Code:

try:
    categories = self.getList(dict[categories])
except KeyError:
    print "No categories found!"

try:
    interests = self.getList(dict[interests])
except KeyError:
    print "No interests found!"

try:
    shops_at = self.getList(dict[shops_at])
except KeyError:
    print "No shops_at found!"

try:
    eats_at = self.getList(dict[eats_at])
except KeyError:
    print "No eats_at found!"
هل كانت مفيدة؟

المحلول

Here's a way to duplicate the functionality of the above code with a loop.

params = {categories: "categories", interests: "interests",
        shops_at: "shops_at", eats_at: "eats_at"}

for k in params:
    try:
        value = self.getList(dict[k])
    except KeyError:
        print "No %s found!" % params[k]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top