return respective values when mutiple keys are passed in dictionary

Chris Angelico rosuav at gmail.com
Mon May 7 09:45:46 EDT 2012


On Mon, May 7, 2012 at 9:31 PM, Nikhil Verma <varma.nikhil22 at gmail.com> wrote:
> mydict = {'a':'apple' , 'b':'boy' ,'c' : 'cat', 'd':'duck','e':'egg'}
>
> Now if i do :-
>
> mydict.get('a')
> 'apple'
>
> What i want is some i pass keys in get and in return i should have all the
> values of those keys which i pass.
>
> ##################
> mydict.get('a','b','c')    ###demo for what i want
> 'apple','boy','cat'        ### Output i want
> #################

Presumably you want to get back a list or tuple, so a list
comprehension is your best bet.

[mydict.get(i) for i in ('a','b','c')]

Incidentally, are you aware that dictionaries can be subscripted? The
get() method is good when you want a default value for anything that
doesn't exist, otherwise you can simply use:

mydict['a']

ChrisA



More information about the Python-list mailing list