[Tutor] selecting elements from dictionary
Steven D'Aprano
steve at pearwood.info
Wed Sep 15 13:27:05 CEST 2010
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
More information about the Tutor
mailing list