Reputation: 53
I have a python dict
a = {
"Ram":(20,"Male"),
"Shyam":(22,"Male"),
"Shruti":(19,"Female"),
}
I want to check whether a name is present in the dict as key and return age based on it otherwise name. So I have written the following function for it
def func(val ):
if val in a:
return ( a[val][ 0 ], True ) # Return age and key in dict?
return ( val, False )
Can I write this in a better way? A one liner or something?
Thanks
Upvotes: 1
Views: 79
Reputation: 42411
One approach would be to make your data structure more informative, to use the get()
method on the dicts, and to abandon the idea of returning a tuple. Regarding the latter, it's not clear why you need the extra boolean value.
persons = {
'Ram' : { 'age' : 20, 'sex' : 'Male' },
'Shyam' : { 'age' : 22, 'sex' : 'Male' },
'Shruti' : { 'age' : 19, 'sex' : 'Female' },
}
def get_age(name):
return persons.get(name, {}).get('age')
names = 'Ram Shruti Foo'.split()
print map(get_age, names) # [20, 19, None]
Upvotes: 0
Reputation: 34146
I would suggest using the function get(key, default)
from dictionaries:
def f(val):
result = a.get(val, False)
return (result[0], True) if result else (val, result)
get(key, default)
returns the correct value if key
is in the dicitonary and returns `default value if it is not.Upvotes: 1
Reputation: 23221
I don't think there's any point in returning val
when you passed it in, especially if you were hoping for a completely different object (the age), so I suggest one of these alternatives:
def func(val):
if val in a:
return a[val][0]
return None
Which could be simplified to (with the exception of returning False
instead of None
:
def func(val):
return val in a and a[val][0]
Or
def func(val):
return a[val][0] # raises KeyError if not found
Upvotes: 0