[Tutor] Dictionary Comprehensions
Lie Ryan
lie.1296 at gmail.com
Fri Dec 4 21:57:49 CET 2009
On 12/5/2009 7:32 AM, 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)}
are you sure you want this?
{'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5}
instead of:
{'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3}
for the former case, you can't, you can't guarantee any sort of ordering
in dictionary. You should use ordered dictionary instead.
For the latter case, it's easy with zip()
dc={y:x for x, y in zip("khalid", range(6))}
as for why python did that, it's because dictionary comprehension is
supposed to have similar semantic with:
dc = {x: y for x, y in lst}
dc = dict( (x, y) for x, y in lst )
so this:
dc={y:x for y in list("khalid") for x in range(6)}
becomes:
dc=dict( (y, x) for y in list("khalid") for x in range(6) )
note that:
>>> [(y, x) for y in list("khalid") for x in range(6)]
[('k', 0), ('k', 1), ('k', 2), ('k', 3), ('k', 4), ('k', 5), ('h', 0),
('h', 1), ('h', 2), ('h', 3), ('h', 4), ('h', 5), ('a', 0), ('a', 1),
('a', 2), ('a', 3), ('a', 4), ('a', 5), ('l', 0), ('l', 1), ('l', 2),
('l', 3), ('l', 4), ('l', 5), ('i', 0), ('i', 1), ('i', 2), ('i', 3),
('i', 4), ('i', 5), ('d', 0), ('d', 1), ('d', 2), ('d', 3), ('d', 4),
('d', 5)]
and when that big list is turned into a dict it gives:
>>> dict(_)
{'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5}
More information about the Tutor
mailing list