How to filter a dictionary ?

Nikhil Verma varma.nikhil22 at gmail.com
Tue Apr 10 02:10:23 EDT 2012


Thanks Shashank . It worked.

On Tue, Apr 10, 2012 at 11:34 AM, Shashank Singh <
shashank.sunny.singh at gmail.com> wrote:

>
>
> On Mon, Apr 9, 2012 at 10:49 PM, Nikhil Verma <varma.nikhil22 at gmail.com>wrote:
>
>>
>> for_patient_type = {37: u'Test', 79: u'Real', 80: u'Real', 81: u'Real',
>> 83: u'Real', 84: u'Real', 91: u'Real', 93: u'Real'}
>>
>> I want if the values are 'Real' give me the keys that have values 'Real'
>> like this.
>>
>> {79:'Real'}
>> {80:'Real'}
>> {81:'Real'}
>> {83:'Real'}
>> {84:'Real'}
>> {91:'Real'}
>> {93:'Real'}
>>
>
> if you want the dict filtered
>
> Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
> [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> for_patient_type = {37: u'Test', 79: u'Real', 80: u'Real', 81:
> u'Real', 83: u'Real', 84: u'Real', 91: u'Real', 93: u'Real'}
> >>> dict((k, for_patient_type[k]) for k in for_patient_type if
> for_patient_type[k] == 'Real')
> {79: u'Real', 80: u'Real', 81: u'Real', 83: u'Real', 84: u'Real', 91:
> u'Real', 93: u'Real'}
> >>>
>
> If you just want the keys
>
> >>> [k for k in for_patient_type if for_patient_type[k] == 'Real']
> [80, 81, 83, 84, 91, 93, 79]
> >>>
>
>
>>
>> I am trying this but its giving me a generator object.
>>
>> In [9]: (k for k,v in for_patient_type.iteritems() if v == 'Real')
>>
>
> Iterating over a dict gives you all the keys, not the key value pairs
>
>
>
> --
> Regards
> Shashank Singh
>   http://www.flipora.com
> http://r <http://www.cse.iitb.ac.in/%7Eshashanksingh>
> ationalpie.wordpress.com
>
>


-- 
Regards
Nikhil Verma
+91-958-273-3156
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120410/6ff03773/attachment-0001.html>


More information about the Python-list mailing list