[Tutor] Dictionary Comprehensions
Christian Witts
cwitts at compuscan.co.za
Mon Dec 7 07:02:28 CET 2009
Khalid Al-Ghamdi wrote:
> Hi everyone!
>
> I'm using python 3.1 and I want to to know why is it when I enter the
> following in a dictionary comprehension:
>
> >>> dc={y:x for y in list("khalid") for x in range(6)}
>
> I get the following:
> {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5}
>
> instead of the expected:
> {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5}
>
> and is there a way to get the target (expected) dictionary using a
> dictionary comprehension.
>
> note that I tried sorted(range(6)) also but to no avail.
>
> thanks
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
Are you maybe looking for `dc = {y:x for y,x in zip('khalid', range(6))}` ?
--
Kind Regards,
Christian Witts
More information about the Tutor
mailing list