Can python create a dictionary from a list comprehension?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 28 04:39:40 EDT 2007


En Mon, 28 May 2007 05:20:16 -0300, Wim Vogelaar  
<wim.vogelaaratmc2worlddotorg at bag.python.org> escribió:

>> Example:
>>
>> a = [1,2,3,4,5,6,7,8,9,10]
>>
>> aDict = dict([(x,x+1) for x in a if x%2==0])
>>
>> print aDict
>>
>
> When I run this program I get:
> {8: 9, 2: 3, 4: 5, 10: 11, 6: 7}
>
> why this output isn't ordered, giving:
> {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }

A dictionary is not ordered, no matter how you create it. If you want to  
process the keys in order:

for key in sorted(aDict):
   print key, '=', aDict[key]

(Note that sorted(aDict) returns a *list*, not a dictionary!)

-- 
Gabriel Genellina




More information about the Python-list mailing list