[Tutor] selecting elements from dictionary
Hs Hs
ilhs_hs at yahoo.com
Wed Sep 15 16:31:54 CEST 2010
Dear Steven,
Thanks for your help.
however I have a question,
using:
for key, value in xdic.items():
if 1 in value and 2 in value or 3 in value:
print key
also print keys that have values such as [1,2,3].
In cases where there is [1,2,3] and [1,2] also reported.
How can I extract those keys that have values only [1,2] and [1,3] exclusively.
>>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2],
>>>75797987:[3,1]}
>>> for key, value in xdic.items():
... if 1 in value and 2 in value or 3 in value:
... print key
...
75797987
75796988
75797478
75797887
Here all 4 keys appear. Instead I want to get only 75797887:[1,2] and
75797987:[3,1]
how can I force this.
thanks again.
________________________________
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Sent: Wed, September 15, 2010 7:27:05 AM
Subject: Re: [Tutor] selecting elements from dictionary
On Wed, 15 Sep 2010 12:10:59 pm Hs Hs wrote:
> I want to print only those items that have [1,2] and [1,3] in any
> order, such as [1,2] or [2,1], [3,1] or [1,3]
>
> >>> for item in xdic.keys():
>
> ... if [1,2] in xdic[item]:
> ... print item
>
> I get a wrong answer,
That's because you ask the wrong question.
[1,2] in xdic[item] doesn't check to see if 1 is in the list, then if 2
is in the list. It looks to see if one of the items is *exactly* [1,2].
>>> [1,2] in [1,2,3,4]
False
>>> [1,2] in [1,2,3,4, [1,2]]
True
> I know the values are there. How can I print
> only those item that have [1,2] and [1,3]
for key, value in xdic.items():
if 1 in value and 2 in value or 3 in value:
print key
--
Steven D'Aprano
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/61f794dc/attachment.html>
More information about the Tutor
mailing list