對字典進行排序

風楚顏發表於2018-06-07

通常我們在日常工作中會對字典進行排序,如下面的這種情況:

這是一個介面返回的json資料:

{"errno":0,"msg":"","result":{"2018-06-01":{"tool":18208,"adapter":18210},"2018-06-02":{"tool":16760,"adapter":16772},"2018-06-03":{"tool":16746,"adapter":16733},"2018-06-04":{"tool":19929,"adapter":19908},"2018-06-05":{"tool":18959,"adapter":18956},"2018-06-06":{"tool":17816,"adapter":17827},"2018-06-07":{"tool":17790,"adapter":17774}}}

我們要取到result對應的值,然後去根據條件進行排序,便於分析觀察資料:

import json
json_data = '{"errno":0,"msg":"","result":{"2018-06-02":{"tool":16760,"adapter":16772},"2018-06-03":{"tool":16746,"adapter":16733},"2018-06-05":{"tool":18959,"adapter":18956},"2018-06-01":{"tool":18208,"adapter":18210},"2018-06-06":{"tool":17816,"adapter":17827},"2018-06-04":{"tool":19929,"adapter":19908},"2018-06-07":{"tool":17790,"adapter":17774}}}'
d1 = json.loads(json_data)
d = d1["result"]

#對字典的key值進行排序
d_list = sorted(d.items(),key=lambda item:item[0])
print(d_list)
#轉換為字典
d_new = {}
for i in d_list:
    d_new[i[0]] = i[1]
print(d_new)

#對字典的value值進行排序
d_list1 = sorted(d.items(),key=lambda item:item[1]['tool'])
print(d_list1)
#轉換為字典
d_new1 = {}
for i in d_list1:
    d_new1[i[0]] = i[1]
print(d_new1)
d_list 返回的資料格式為列表形式。


相關文章