2017年5月10日 星期三

python dictionary items 未依序排列問題

import collections

s = {}
for i in range(0,36,2):
    s.update({i:str(i)*10})

sorted_s = collections.OrderedDict(sorted(s.items()))
print(s)
print('-------')
print(sorted_s)
print('=======')
for i, j in sorted_s.items():
    print('%s:%s' % (i,j))
將 dictionary s 重新排序後, 輸出次序就能正常囉~
{0: '0000000000', 32: '32323232323232323232', 2: '2222222222', 4: '4444444444', 6: '6666666666', 8: '8888888888', 10: '10101010101010101010', 12: '12121212121212121212', 34: '34343434343434343434', 14: '14141414141414141414', 16: '16161616161616161616', 18: '18181818181818181818', 20: '20202020202020202020', 22: '22222222222222222222', 24: '24242424242424242424', 26: '26262626262626262626', 28: '28282828282828282828', 30: '30303030303030303030'}
-------
OrderedDict([(0, '0000000000'), (2, '2222222222'), (4, '4444444444'), (6, '6666666666'), (8, '8888888888'), (10, '10101010101010101010'), (12, '12121212121212121212'), (14, '14141414141414141414'), (16, '16161616161616161616'), (18, '18181818181818181818'), (20, '20202020202020202020'), (22, '22222222222222222222'), (24, '24242424242424242424'), (26, '26262626262626262626'), (28, '28282828282828282828'), (30, '30303030303030303030'), (32, '32323232323232323232'), (34, '34343434343434343434')])
=======
0:0000000000
2:2222222222
4:4444444444
6:6666666666
8:8888888888
10:10101010101010101010
12:12121212121212121212
14:14141414141414141414
16:16161616161616161616
18:18181818181818181818
20:20202020202020202020
22:22222222222222222222
24:24242424242424242424
26:26262626262626262626
28:28282828282828282828
30:30303030303030303030
32:32323232323232323232
34:34343434343434343434