一般常規(guī)的我們保存數(shù)據(jù)為dict類型時(shí),系統(tǒng)會(huì)自動(dòng)幫我們排序;但有時(shí)我們想按照輸入順序的key:value保存到dict中,而不想要改變順序,則我們可以通過使用collecions,進(jìn)行排序。
collections是一個(gè)python的內(nèi)建模塊。
示例如下:
# -*- coding:utf-8 -*- #dic = {} dic = dict() dic['b'] = 1 dic['a'] = 2 dic['b0'] = 3 dic['a1'] = 4 print("dic is:",dic.items()) import json jsons = json.dumps(dic) print("jsons:",jsons) 結(jié)果: ('dic is:', [('a', 2), ('a1', 4), ('b', 1), ('b0', 3)]) ('jsons:', '{"a": 2, "a1": 4, "b": 1, "b0": 3}') 修改后: import collections dic = collections.OrderedDict() #dic = {} dic['b'] = 1 dic['a'] = 2 dic['b0'] = 3 dic['a1'] = 4 print("dic is:",dic.items()) import json jsons = json.dumps(dic) print("jsons:",jsons) 結(jié)果: ('dic is:', [('b', 1), ('a', 2), ('b0', 3), ('a1', 4)]) ('jsons:', '{"b": 1, "a": 2, "b0": 3, "a1": 4}')
網(wǎng)站名稱:在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式-創(chuàng)新互聯(lián)
URL網(wǎng)址:http://chinadenli.net/article26/deejjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、動(dòng)態(tài)網(wǎng)站、移動(dòng)網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、搜索引擎優(yōu)化、網(wǎng)頁設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容