Reputation: 395
I have a dictionary and I want to add some index of the dictionary to variables.
I know that try except is more pythonic than else if. And I tried with try except and it's works perfectly but I have a lot of key to check and I can't figure out of which code is more pythonic
Here is my dictionary :
test = {"token":"eating", "stemm": "eat", "lemm": "eat", "pos":"VPP"}
def method_one(test):
try:
token = test["token"]
except KeyError:
token = None
try:
stemm = test["stemm"]
except KeyError:
stemm = None
def method_two(test):
token = None
stemm = None
if "token" in test:
token = test["token"]
if "stemm" in test:
stemm = test["stemm"]
I also tried one try except for all but when one failed, I can't know which one is failing so this is useless.
Any ideas of a third method? Or method one is the good one?
Upvotes: 0
Views: 2439
Reputation: 1806
There is a direct lookup construct where create a set of valid keys that should exist in the dictionary
test = {"token":"eating", "stemm": "eat", "lemm": "eat", "pos":"VPP"}
def validate(d, valkeys):
keyset = set(test.keys())
if valkeys.issubset(keyset):
return True
else:
return False
if __name__ == "__main__":
val = set(["token", "stemm"])
inval = set(["token", "stemm", "st"])
assert validate(test, val) == True
assert validate(test, inval) == False
Upvotes: 0
Reputation: 6590
dict
has get
method that will return value
or None
. you could do item = dict.get(key)
and this will return
either the value
(if the key
exists) or None
otherwise, which is what you are looking for it seems :)
>>> d = {'foo': 'bar'}
>>> d.get('foo')
'bar'
>>> item = d.get('fooo')
>>> item is None
True
Upvotes: 2