0

Python noob so I might be going about this the wrong way

I want to use a try/except block to find if a value in a dict isn't set like

try:
    if entry['VALUE1'] == None: void()
    if entry['VALUE2'] == None: void()
except KeyError:
    print "Values not Found"

Of course the 'void' function doesn't exist, is there anything I can do to get round this so that code will work properly

2
  • It's not clear from this question, but maybe what you're looking for is a defaultdict? Whenever you access an entry that doesn't exist, it's automatically added with a default value, so you don't have to worry when doing things like entry['VALUE1'] += value. Commented Jun 13, 2011 at 3:50
  • Just as a side note, its nicer to do if entry['VALUE1'] is None: Commented Jun 13, 2011 at 8:21

5 Answers 5

8

Try replacing void() with pass.

Of course, in practice, you can just do if key in some_dict:. But if you ever need a "do nothing" in a block, pass is what you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

3

Try:

if "VALUE1" in entry:
    foo()

to determine if the "VALUE1" string is in the set of keys of the entry dict.

Your logic would probably look something like:

if "VALUE1" not in entry or "VALUE2" not in entry:
    print "Values not found"

The try block is completely unnecessary for this test.

Comments

0
if entry.has_key('VALUE1'):
 do_something()

or

if 'VALUE1' in entry:
 do_something()

Comments

0

I would suggest making a function to help you out:

contains_all_keys = lambda d, keys: reduce(lambda a, b: a and b, map(lambda k: k in d, keys))
di = {'a':'some val', 'b':'some other val'}
if contains_all_keys(di, ['a', 'b']):
    print 'a and b present'
if not contains_all_keys(di, ['a', 'b', 'c']):
    print 'missing keys'

2 Comments

I think both "all(key in di for key in ['a','b'])" and "set(['a','b']).issubset(di)" are clearer than a nested triple lambda with a map and a reduce.
hah I think you're absolutely right. I didn't know about all(), thats quite nice with list comprehensions.
0

If you just want to evoke the exception, through a key lookup, the if is not neccesary. It's sufficient to just express the lookup on a line by itself, such as:

>>> a = {}
>>> a['value']
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
KeyError: 'value'
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.