[Tutor] How to print corresponding keys in Dictionary

Raúl Cumplido raulcumplido at gmail.com
Mon Oct 24 15:18:11 CEST 2011


Hi,

Keys are unique in a dictionaire but values aren't. What do you want to
print if you have the next dictionaire:

dict = {'a' : 1, 'b' : 1}

If you are using python 2.7 you can use dictionary comprehensions to swap
keys for values:

>>> d={'a':1,'b':2,'c':3}
>>> new_dict = {v : k for k,v in d.iteritems()}
>>> new_dict
{1: 'a', 2: 'b', 3: 'c'}

but if you're values are repeated you will loose some keys:
>>> dict = {'a' : 1, 'b':1}
>>> {v : k for k,v in dict.iteritems()}
{1: 'b'}

HTH,

Raúl

On Mon, Oct 24, 2011 at 3:10 PM, Praveen Singh <c2praveen30jun at gmail.com>wrote:

> In Dictionary-
> How to print corresponding keys if the values of dictionary is given??
>
> -d={'a':1,'b':2,'c':3}
> -i can print the corresponding values by using get() method-
> - d.get('a')
> -1
>
> What if i have to print reverse???
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Raúl Cumplido
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111024/0e20efe7/attachment-0001.html>


More information about the Tutor mailing list